在单元测试中模拟Mapper.Map() [英] Mocking Mapper.Map() in Unit Testing
问题描述
我的控制器中有以下代码行,需要对此进行设置以进行单元测试.
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();
我在控制
this.mapperMock.Setup(x => x.Map<A_Class, B_Class>(AAA)).Returns(expectedResult);
谁能建议应该是AAA,应该是什么?在我的控制器中,我的linq在Data中的A_Class的foreach对象起作用.如何在UnitTest中设置
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
推荐答案
如果无论传递了什么A_Class
值,都要返回假的expectedResult
:
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);
如果您想更具体一点,例如只需为属性A_Class
返回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);
请注意,如果没有设置匹配,Moq将返回默认值,对于引用类型,默认值为null
.
Note that if no setup matches, Moq will return a default value, which will be null
for a reference type.
这篇关于在单元测试中模拟Mapper.Map()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!