Moq test void method

Hey. I am new to Moq testing and it is not easy to make a simple statement. I am using the interface

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

Moq for IAdd interface:

  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 not valid, it does not return any value for Assert with. How can I approve this setting?

+8
c # unit-testing nunit moq
source share
2 answers

Why is it taunting? It is used to verify that the SUT (system under test) interacts correctly with its dependencies (which should be a mockery). Correct interaction means invoking the correct dependency members with the correct parameters.

You should never assert the value returned by mock . This is a dummy value that is not related to the production code. The only value you should state for is the value returned by SUT. SUT is the only thing you should write statements for.

Also, you should never test interfaces . Because there is nothing to test. An interface is just an API description. It has no implementation. So stop and think about what code you are testing here? Is this the real code that runs in your application?

So, you should mock the IAdd interface only to test an object that uses the IAdd interface.

+18
source share

It is better to provide more context, but it is usually used as follows:

 var mockAdd = new Mock<IAdd>(); mockAdd.Setup(x => x.Add(1, 2)).Verifiable(); //do something here what is using mockAdd.Add mockAdd.VerifyAll(); 
+14
source share

All Articles