gpt4 book ai didi

c# - 如何在 Controller 中模拟 Automapper (IMapper)

转载 作者:太空狗 更新时间:2023-10-29 21:11:56 24 4
gpt4 key购买 nike

我正在尝试为我现有的 MVC Web 应用程序编写单元测试。因为我在 automapper (IMapper) 中遇到了一些问题,每当我使用 map 函数时,它都会返回 null 值。

我的 Controller 代码:

public class UserAdministrationController : BaseController
{
private readonly iUserService _userService;
private readonly IMapper _mapper;

public NewsController(iUserService userService, IMapper mapper)
{
_userService = userService;
_mapper = mapper;
}

public ActionResult Create(int CompanyID == 0)
{
UserDetail data = _userService(CompanyID);
var Modeldata = _mapper.Map<UserDetailViewModel, UserDetail>(data);
return View(Modeldata);
}
}

模拟映射代码:

public class MappingDataTest : CommonTestData
{
public Mock<IMapper> MappingData()
{
var mappingService = new Mock<IMapper>();
UserDetailViewModel interview = getUserDetailViewModel(); // get value of UserDetailViewModel
UserDetail im = getUserDetail(); // get value of UserDetails

mappingService.Setup(m => m.Map<UserDetail, UserDetailViewModel>(im)).Returns(interview);
mappingService.Setup(m => m.Map<UserDetailViewModel, UserDetail>(interview)).Returns(im);

return mappingService;
}
}

模拟代码:

[TestClass]
public class UserAdminControllerTest
{
private MappingDataTest _common;

[TestInitialize]
public void TestCommonData()
{
_common = new MappingDataTest();
}

[TestMethod]
public void UserCreate()
{
//Arrange
UserAdministrationController controller = new UserAdministrationController(_common.mockUserService().Object, _common.MappingData().Object);
controller.ControllerContext = _common.GetUserIdentity(controller);

// Act
ViewResult newResult = controller.Create() as ViewResult;

// Assert
Assert.IsNotNull(newResult);
}
}

Mapper 不工作,它总是在 Controller 中显示 null 值。请帮助我。提前致谢。

最佳答案

我建议不要模拟 AutoMapper。一个 Controller 单元测试没有太大值(value),这类似于模拟 JSON 序列化程序。只需使用真实的东西即可。

关于c# - 如何在 Controller 中模拟 Automapper (IMapper),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43817242/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com