使用 Moq 验证方法调用 [英] Verify a method call using Moq
问题描述
我对 C# 中的单元测试和学习使用 Moq 相当陌生.下面是我要测试的课程.
I am fairly new to unit testing in C# and learning to use Moq. Below is the class that I am trying to test.
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...
}
}
下面是我的测试类:
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>()));
}
}
我收到以下异常:
Expected invocation on the mock at least once, but was never performed
No setups configured.
No invocations performed..
我只想验证是否正在调用方法MyMethod".我错过了什么吗?
I just want to verify if the method "MyMethod" is being called or not. Am I missing something?
推荐答案
您正在检查错误的方法.Moq 要求您设置(然后选择验证)依赖类中的方法.
You're checking the wrong method. Moq requires that you Setup (and then optionally Verify) the method in the dependency class.
你应该做更多这样的事情:
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();
}
}
换句话说,您正在验证调用 MyClass#MyMethod
,您的类肯定会在该过程中调用一次 SomeClass#DoSomething
.请注意,您不需要 Times
参数;我只是在展示它的价值.
In other words, you are verifying that calling MyClass#MyMethod
, your class will definitely call SomeClass#DoSomething
once in that process. Note that you don't need the Times
argument; I was just demonstrating its value.
这篇关于使用 Moq 验证方法调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!