Check method call with Moq

I am new to unit testing in C # and have learned to use Moq. Below is the class I'm 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... } } 

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 check if the "MyMethod" method is called or not. Did I miss something?

Thanks in advance!

+50
methods c # testing moq
Feb 03 '12 at 23:01
source share
1 answer

You are checking the wrong method. Moq requires that you install (and then optionally Verify) a method in the dependency class.

You have to do something more:

 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 verify that calling MyClass#MyMethod , your class will definitely call SomeClass#DoSomething once in the process. Note: you do not need the Times argument; I just demonstrated its value.

+76
Feb 03 2018-12-23T00:
source share



All Articles