Moq伪造一种方法,但使用另一种方法的实际实现

编程入门 行业动态 更新时间:2024-10-23 15:27:58
本文介绍了Moq伪造一种方法,但使用另一种方法的实际实现的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

给出具有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伪造一种方法,但使用另一种方法的实际实现

本文发布于:2023-11-27 03:06:46,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1636310.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:种方法   方法   Moq

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!