Mocking Mapper.Map() in Unit Testing

二次信任 提交于 2020-01-05 04:51:10

问题


I have following line of code in my controller and need to Setup this for Unit Test.

var result = data.ToList().Select(x=> this.mapper.Map<A_Class, B_Class>   (x)).ToList();

I am doign something like following

  this.mapperMock.Setup(x => x.Map<A_Class, B_Class>(AAA)).Returns(expectedResult);

Can anyone suggest what should be AAA and what should be expectedResult? In my controller my linq works foreach object of A_Class in Data. How can this be setup in UnitTest


回答1:


If you want to return your fake expectedResult no matter what value of A_Class is passed:

mapperMock.Setup(x => x.Map<A_Class, B_Class>(It.IsAny<A_Class>))
          .Returns(expectedResult);

If you want to be more specific, e.g. just return expectedResult for mapped A_Class with a property value of 'foo':

mapperMock.Setup(
         x => x.Map<A_Class, B_Class>(It.Is<A_Class>(_ => a.Property == "foo")))
    .Returns(expectedResult);

Note that if no setup matches, Moq will return a default value, which will be null for a reference type.



来源:https://stackoverflow.com/questions/22984530/mocking-mapper-map-in-unit-testing

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!