C# 使用 Moq 验证方法调用
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9136674/
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
Verify a method call using Moq
提问by user591410
I am fairly new to unit testing in C# and learning to use Moq. Below is the class that I am trying to test.
我对 C# 中的单元测试和学习使用 Moq 相当陌生。下面是我要测试的课程。
class MyClass
{
SomeClass someClass;
public MyClass(SomeClass someClass)
{
this.someClass = someClass;
}
public void MyMethod(string method)
{
method = "test"
someClass.DoSomething(method);
}
}
class Someclass
{
public DoSomething(string method)
{
// do something...
}
}
Below is my TestClass:
下面是我的测试类:
class MyClassTest
{
[TestMethod()]
public void MyMethodTest()
{
string action="test";
Mock<SomeClass> mockSomeClass = new Mock<SomeClass>();
mockSomeClass.SetUp(a => a.DoSomething(action));
MyClass myClass = new MyClass(mockSomeClass.Object);
myClass.MyMethod(action);
mockSomeClass.Verify(v => v.DoSomething(It.IsAny<string>()));
}
}
I get the following exception:
我收到以下异常:
Expected invocation on the mock at least once, but was never performed
No setups configured.
No invocations performed..
I just want to verify if the method "MyMethod" is being called or not. Am I missing something?
我只想验证是否正在调用方法“MyMethod”。我错过了什么吗?
采纳答案by Platinum Azure
You're checking the wrong method. Moq requires that you Setup (and then optionally Verify) the method in the dependency class.
您正在检查错误的方法。Moq 要求您设置(然后选择验证)依赖项类中的方法。
You should be doing something more like this:
你应该做更多这样的事情:
class MyClassTest
{
[TestMethod]
public void MyMethodTest()
{
string action = "test";
Mock<SomeClass> mockSomeClass = new Mock<SomeClass>();
mockSomeClass.Setup(mock => mock.DoSomething());
MyClass myClass = new MyClass(mockSomeClass.Object);
myClass.MyMethod(action);
// Explicitly verify each expectation...
mockSomeClass.Verify(mock => mock.DoSomething(), Times.Once());
// ...or verify everything.
// mockSomeClass.VerifyAll();
}
}
In other words, you are verifying that calling MyClass#MyMethod, your class will definitely call SomeClass#DoSomethingonce in that process. Note that you don't need the Timesargument; I was just demonstrating its value.
换句话说,您正在验证调用MyClass#MyMethod,您的类肯定会SomeClass#DoSomething在该过程中调用一次。请注意,您不需要Times参数;我只是在证明它的价值。

