验证使用起订量的方法调用 [英] Verify a method call using Moq
问题描述
我在C#相当新的单元测试和学习使用起订量。 。下面是我想测试类
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...
}
}
下面是我的TestClass:
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..
我只是想验证该方法的MyMethod是被称为与否。我缺少的东西吗?
I just want to verify if the method "MyMethod" is being called or not. Am I missing something?
在此先感谢!
推荐答案
您'重新检查错误的方法。 。起订量要求您设置(然后有选择地验证)在依赖类中的方法
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
一次。请注意,您不需要时间
参数;我只是展示了其价值。
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.
这篇关于验证使用起订量的方法调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!