mocking sibling methods
Assuming I have the following I wish to unit test:
class Foo: IAMethods, IBMethods
{
// Implementation of IAMethods.A()
public int A()
{
return B() + 1;
}
// Implementation of IBMethods.B()
public int B()
{
开发者_JAVA技巧return 1;
}
}
How can I mock B() when calling A()? I am assuming that the design of the class is probably incorrect. I have a situation where we have a a service layer with a lot of interfaces, and occasionally one service layer function will call another (using the same or a different interface). I'm not certain how you can mock the other service layer methods since you can't really dependency inject something into itself. Can anyone please give me some clarity on this situation and recommendations?
Have a look at partial mocks for Moq (RhinoMocks has something similar). At a very minimum you have to have it virtual.
public virtual int B()
{
return 1;
}
In your test...
Mock<Foo> mock = Mock<Foo>();
mock.Setup(m => m.B()).Returns(5);
int result = mock.Object.A(4);
Assert.That(result, Is.EqualTo(9));
C# does not allow mixins but you can have each interface implemented by separate classes then the top level service class can delegate the calls to them through composition.
You can create Visual Studio item templates to help you mocking. See more at Creating Item Templates.
Regards, John
精彩评论