我在这种情况下嘲笑:
class A
{
public IB B {get; set;}
}
interface IB
{
//methods
}
class B : IB
{
//IB methods
}
public SimpleMockTest()
{
var mockIB = new Mock<IB>();
var a = new A{B=mockIB.Object};
//do stuff with A, then verify methods on IB were called
}
public TheKindOfTestIWantToDo()
{
var actualB = new B();
var mockIB = new Mock<IB>();
var splitter = new Splitter<IB>(actualB, mockIB.Object); //I need something like this
var a = new A{B=splitter};
//do stuff with A, methods invoked on splitter IB get passed to both supplied instances
//of IB (actualB, and the mockIB). Allowing me to verify the calls as well as have the methods invoked on the actual B object.
//OR:
var mockIB2 = new Mock<IB>(actualB); //behaviour is dictated by the actual, but allows verification
var a2 = new A{B=mockIB2.Object};
}
所以我在某种代理工厂之后,通用支持接口并在多个接口上调用相同的方法。当然,当一个方法返回一个值时,每个方法都需要返回相同的值,或者一个方法需要预先确定。
我希望在测试期间有效地窥探接口调用,但不会将模拟作为行的结尾。
如果它有任何不同,我会使用Moq。
答案 0 :(得分:4)
据我所知,actualB
上的所有方法都无法做到这一点。
我想你想要这样的东西:
public TheKindOfTestIWantToDo()
{
var actualB = new B();
var mockIB = new Mock<IB>();
mockIB.Setup(b => b.Foo()).Returns(() => actualB.Foo())
var a = new A { B = mockIB };
//do stuff with A, methods invoked on splitter IB get passed to both supplied instances
//of IB (actualB, and the mockIB). Allowing me to verify the calls as well as have the methods invoked on the actual B object.
}
但您应该重新考虑您的单元测试策略。 A
的行为应该是可测试的,而不依赖于B
的行为。尝试让mockIB
返回特定值,然后为B
编写一组不同的测试。