我对 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... } }
下面是我的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>())); } }
我得到以下异常:
Expected invocation on the mock at least once, but was never performed No setups configured. No invocations performed..
我只想验证是否正在调用方法“MyMethod”。我错过了什么吗?
您正在检查错误的方法。Moq 要求您设置(然后可选地验证)依赖类中的方法。
你应该做更多这样的事情:
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参数;我只是在展示它的价值。
MyClass#MyMethod
SomeClass#DoSomething
Times