C# 最小起订量测试无效方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15062403/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Moq testing void method
提问by J. Davidson
Hi I am new to Moq testing and having hard time to do a simple assertion. I am using an interface
嗨,我是 Moq 测试的新手,很难做一个简单的断言。我正在使用一个接口
public interface IAdd
{
void add(int a, int b);
}
Moq for the IAdd
interface is:
IAdd
接口的最小起订量是:
Mock<IAdd> mockadd = new Mock<IAdd>();
mockadd.Setup(x => x.add(It.IsAny<int>(), It.IsAny<int>()).callback((int a, int b) => { a+b;});
IAdd testing = mockadd.Object;
Since the add
method is void, it doesn't return any value to Assert with. How can I assert this setup?
由于该add
方法是无效的,因此它不会向 Assert with 返回任何值。我怎样才能断言这个设置?
回答by Pavel Bakshy
Better to provide more context, but typically it used like this:
最好提供更多的上下文,但通常它是这样使用的:
var mockAdd = new Mock<IAdd>();
mockAdd.Setup(x => x.Add(1, 2)).Verifiable();
//do something here what is using mockAdd.Add
mockAdd.VerifyAll();
回答by Sergey Berezovskiy
Why mocking is used? It used for verifying that SUT (system under test) interacts correctly with its dependencies (which should be mocked). Correct interaction means calling correct dependency members with correct parameters.
为什么使用嘲讽?它用于验证 SUT(被测系统)与其依赖项(应该被模拟)正确交互。正确的交互意味着使用正确的参数调用正确的依赖成员。
You should never assert on value returned by mock. That is dummy value which has no relation to production code. The only value you should assert on is a value returned by SUT. SUT is the only thing you should write assertions for.
你永远不应该对 mock 返回的值进行断言。这是与生产代码无关的虚拟值。您应该断言的唯一值是 SUT 返回的值。SUT 是您应该为其编写断言的唯一内容。
Also you should never test interfaces. Because there is nothing to test. Interface is just a API description. It has no implementation. So, stop and think about what code are you testing here? Is this is a real code, which executed in your application?
此外,您永远不应该测试接口。因为没有什么可测试的。接口只是一个 API 描述。它没有实现。所以,停下来想想你在这里测试什么代码?这是在您的应用程序中执行的真实代码吗?
So, you should mock IAdd
interface only for testing object which uses IAdd
interface.
因此,您应该IAdd
只为使用IAdd
接口的测试对象模拟接口。