Verify a method call using Moq

前端 未结 1 875
不思量自难忘°
不思量自难忘° 2020-12-12 19:38

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;
    publ         


        
相关标签:
1条回答
  • 2020-12-12 20:41

    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();
        }
    }
    

    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.

    0 讨论(0)
提交回复
热议问题