"is it a good practice to mock automapper in unit tests?" Code Answer

4

i think the issue here is that the test is badly written for what it is actually trying to achieve which is testing service.get().

the way i would write this test is as follows:

[testmethod]
public void test()
{
  var expected = new serviceitem();

  var mockdomain = new mock<idomain>();
  var expecteddomainreturn = new domainitem(0); //illustrative purposes only
  mockdomain.setup(x => x.domaincall(0)).returns(expecteddomainreturn); //illustrative purposes only

  var mockmapper = new mock<imapper>();
  mockmapper.setup(x => x.map<domainitem, serviceitem>(it.isany<domainitem>()))
      .returns(expected);    


  var service = new service(mockdomain.object, mockmapper.object);
  var result = service.get(0);

  mockdomain.verify(x => x.domaincall(0), times.once);
  mockmapper.verify(x => x.map<domainitem, serviceitem>(expecteddomainreturn), times.once);
}

this test instead of not really checking the functionality of the service.get(), checks that the parameters passed are correct for the individual dependency calls based on the responses. you are thus not testing automapper itself and should not need to.

checking result is basically useless but will get the code coverage up.

By Sethunath on May 31 2022

Answers related to “is it a good practice to mock automapper in unit tests?”

Only authorized users can answer the Search term. Please sign in first, or register a free account.