给出具有Method1()和Method2()的接口IService.
我想测试当Method1()抛出Exception时,调用Method2()并返回给定值.
I want to test that when Method1() throws an Exception, Method2() is called and returns a given value.
(抛出Method1()时会调用Method2()).
因此,我需要使用伪造的Method1()测试真实的Method2(),它们是同一接口的方法.
Therefore I need to test a real Method2() with a fake Method1(), they are methods of the same interface.
这是我的测试代码:
MBase sut.MethodX()是唯一的入口点.它使用IService.
MBase sut.MethodX() is the only entry point. It uses IService.
我的目的是断言Method2()返回某物.
// Arrange // Fake bytes in. var networkStreamMock = new Mock<INetworkStream>(); networkStreamMock.Method1(x => x.Read(It.IsAny<byte[]>(), It.IsAny<int>(), It.IsAny<int>())).Returns(It.IsAny<byte[]>()); // Force throw TimeoutException. var mock = new Mock<IService>(); mock.Setup(x => x.Method1(new Message { Xml = Xml, } )).Throws<TimeoutException>(); // Check Method 2 is called. (this is done in its own test so commented out) // mock.Setup(m => m.Method2(It.IsAny<Message>())).Verifiable(); // New MBase. IKernel kernel = new StandardKernel(new FakeBindings()); kernel.Rebind<IService>().ToConstant(mock.Object); MBase sut = kernel.Get<M>(); // Act sut.MethodX(networkStreamMock.Object); // Here I would like to assert on the return value of Method2 mock.Verify(m => m.Method2(It.IsAny<Message>()));Moq或其他模拟框架是否可能?我该怎么做? 我可以使用Method1()的伪实现和Method2()的真实实现创建手动模拟,但是我想知道是否有更好的方法.
Is this possible with Moq or another mocking framework? How do I do it? I can create a manual mock with a fake implementation of Method1() and a real implementation of Method2() but I wonder if there is a better approach.
我已经单独测试了IService,但现在我想测试它与MBase的交互.
I have already tested IService in isolation but I now wish to test it's interaction with MBase.
推荐答案您可以执行以下操作:
var mock = new Mock<MyNetworkStream>(){ CallBase = true }; mock.Setup(m => m.Method1....上面的代码将对未明确设置的任何方法/属性使用MyNetworkStream的实际实现. IE.它会调用真实的Method2(),而Method1()将是模拟版本.
The above code will use the real implementation of MyNetworkStream for any method/property which is not explicitly setup. I.e. it'll call the real Method2(), while the Method1() will be the mocked version.
CallBase=true通常用于测试抽象类(如果是对还是错,不在此问题范围之内).
CallBase=true is usually meant to test abstract classes (if this is right or wrong, is out of the scope of this question).
更多推荐
Moq伪造一种方法,但使用另一种方法的实际实现
发布评论