Moq testing void method

32,239

Solution 1

Why mocking is used? It used for verifying that SUT (system under test) interacts correctly with its dependencies (which should be mocked). Correct interaction means calling correct dependency members with correct parameters.

You should never assert on value returned by mock. That is dummy value which has no relation to production code. The only value you should assert on is a value returned by SUT. SUT is the only thing you should write assertions for.

Also you should never test interfaces. Because there is nothing to test. Interface is just a API description. It has no implementation. So, stop and think about what code are you testing here? Is this is a real code, which executed in your application?

So, you should mock IAdd interface only for testing object which uses IAdd interface.

Solution 2

Better to provide more context, but typically it used like this:

var mockAdd = new Mock<IAdd>();
mockAdd.Setup(x => x.Add(1, 2)).Verifiable();

//do something here what is using mockAdd.Add

mockAdd.VerifyAll();
Share:
32,239
J. Davidson
Author by

J. Davidson

Updated on August 17, 2020

Comments

  • J. Davidson
    J. Davidson almost 4 years

    Hi I am new to Moq testing and having hard time to do a simple assertion. I am using an interface

     public interface IAdd
     {
         void add(int a, int b);
     }
    

    Moq for the IAdd interface is:

      Mock<IAdd> mockadd = new Mock<IAdd>();
      mockadd.Setup(x => x.add(It.IsAny<int>(), It.IsAny<int>()).callback((int a, int b) => { a+b;});
      IAdd testing = mockadd.Object;
    

    Since the add method is void, it doesn't return any value to Assert with. How can I assert this setup?

  • Thiago Melo
    Thiago Melo over 7 years
    Hi Sergey, I'm new on this mock tests. I would like to avoid the void method to execute, the method updates the database, is theer a better way of doing so?
  • Maddy
    Maddy over 6 years
    Pavel, can you explain a little more about //do something here what is using mockAdd.Add. I am stuck on a similar problem and not sure what to add to "//do something here what is using mockAdd.Add"
  • cd491415
    cd491415 over 5 years
    would be nice to add some explanation to the commented out part @PavelBakshy