这是重复的吗?我将如何使用 COM OLE 对象进行 TDD
EDIT: Looks like you're asking the same question, but to validate your mocking code (OOPS).
You're not quite there for your mocking scenario. You're in the right that you want to isolate external dependencies, and your COM object certainly meets that criteria. Though I'm not a moq guy (I prefer RhinoMocks) the idea behind mocks is interaction testing...
Interaction testing is about how cohesive sets of objects work together. A valid test in this scenario would be to write a test for the component that is dependent on your COM object's behavior.
In this case, your "Table" which acts like a wrapper for your COM object, is also dependent on the COM object's behavior. For argument sake, let's say your Table object performs custom logic against the values that are returned from your COM object.
Now you can write isolated tests for your Table object while simulating your COM object's behavior using Mocks.
public class Table
{
public Table(IMapInfo map)
{
_map = map;
}
public string Name
{
get
{
string value = _map.Eval("myexpression");
if (String.IsNullOrEmpty(value))
{
value = "none";
}
return value;
}
}
private IMapInfo _map;
}
[TestFixture]
public class TableFixture // is this a pun?
{
[Test]
public void CanHandleNullsFromCOM()
{
MockRepository mocks = new MockRepository(); // rhino mocks, btw
IMapInfo map = mocks.CreateMock<IMapInfo>();
using (mocks.Record())
{
Expect.Call(map.Eval("myexpression").Return(null);
}
using (mocks.PlayBack())
{
Table table = new Table(map);
Assert.AreEqual("none", table.Name, "We didn't handle nulls correctly.");
}
mocks.verify();
}
}
Maybe your COM object throws exceptions when it's called, or maybe it doesn't handle string expressions very well. We're actually testing how our Table object interacts with the IMapInfo without being tied to the COM object's implementation. We're also enforcing a relationship between Table and IMapInfo in that the IMapInfo object must be called during the test.
Hope this helps.