gpt4 book ai didi

asp.net-mvc - 使用 AutoMapper 对 Controller 进行单元测试

转载 作者:行者123 更新时间:2023-12-03 20:28:49 26 4
gpt4 key购买 nike

我正在尝试对使用 AutoMapping 的 UpdateUser Controller 进行单元测试。这是 Controller 的代码

更新用户 Controller

    private readonly IUnitOfWork _unitOfWork;
private readonly IWebSecurity _webSecurity;
private readonly IOAuthWebSecurity _oAuthWebSecurity;
private readonly IMapper _mapper;

public AccountController()
{
_unitOfWork = new UnitOfWork();
_webSecurity = new WebSecurityWrapper();
_oAuthWebSecurity = new OAuthWebSecurityWrapper();
_mapper = new MapperWrapper();
}

public AccountController(IUnitOfWork unitOfWork, IWebSecurity webSecurity, IOAuthWebSecurity oAuthWebSecurity, IMapper mapper)
{
_unitOfWork = unitOfWork;
_webSecurity = webSecurity;
_oAuthWebSecurity = oAuthWebSecurity;
_mapper = mapper;
}

//
// Post: /Account/UpdateUser
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult UpdateUser(UpdateUserModel model)
{
if (ModelState.IsValid)
{
// Attempt to register the user
try
{
var userToUpdate = _unitOfWork.UserRepository.GetByID(_webSecurity.CurrentUserId);
var mappedModel = _mapper.Map(model, userToUpdate);

**mappedModel will return null when run in test but fine otherwise (e.g. debug)**


_unitOfWork.UserRepository.Update(mappedModel);
_unitOfWork.Save();

return RedirectToAction("Index", "Home");
}
catch (MembershipCreateUserException e)
{
ModelState.AddModelError("", ErrorCodeToString(e.StatusCode));
}
}
return View(model);
}

这是我的单元测试
更新用户 Controller 测试
[Fact]
public void UserRepository_Update_User_Success()
{
Controller = new AccountController(UnitOfWork, WebSecurity.Object, OAuthWebSecurity.Object, Mapper);
const string emailAsUserName = "user@username.com";
const string password = "password";
const string email = "email@email.com";
const string emailNew = "newEmail@email.com";
const string firstName = "first name";
const string firstNameNew = "new first name";
const string lastName = "last name";
const string lastNameNew = "new last name";

var updatedUser = new User
{
Email = emailNew,
FirstName = firstNameNew,
LastName = lastNameNew,
UserName = emailAsUserName
};

WebSecurity.Setup(
s =>
s.CreateUserAndAccount(emailAsUserName, password,
new { FirstName = firstName, LastName = lastName, Email = email }, false))
.Returns(emailAsUserName);
updatedUser.UserId = WebSecurity.Object.CurrentUserId;

UnitOfWork.UserRepository.Update(updatedUser);
UnitOfWork.Save();

var actualUser = UnitOfWork.UserRepository.GetByID(updatedUser.UserId);
Assert.Equal(updatedUser, actualUser);

var model = new UpdateUserModel
{
Email = emailAsUserName,
ConfirmEmail = emailAsUserName,
FirstName = firstName,
LastName = lastName
};
var result = Controller.UpdateUser(model) as RedirectToRouteResult;
Assert.NotNull(result);
}

我有一种直觉,当在测试模式下运行时,映射器不会查看我在 Global.asax 中设置的映射器配置。由于该错误仅在执行单元测试期间发生,而不是在按原样运行网站时发生。我创建了一个 IMappaer 接口(interface)作为 DI,因此我可以模拟它以进行测试。我使用 Moq for Mocking 和 xUnit 作为测试框架,我还安装了尚未使用的 AutoMoq。任何的想法?谢谢你看我的长文。希望有人可以提供帮助,一直在挠头几个小时并阅读了很多帖子。

最佳答案

在您的测试中,您需要创建 IMapper 的模拟版本。接口(interface),否则你不是单元测试,你是集成测试。那你只需要做一个简单的mockMapper.Setup(m => m.Map(something, somethingElse)).Returns(anotherThing) .

如果你想在测试中使用真正的 AutoMapper 实现,那么你需要先设置它。您的测试不会自动获取您的 Global.asax ,您还必须在测试中设置映射。当我像这样进行集成测试时,我通常有一个静态的 AutoMapperConfiguration.Configure()我在测试夹具设置中调用的方法。对于 NUnit,这是 [TestFixtureSetUp]方法,我认为对于 xUnit,您只需将其放在构造函数中即可。

关于asp.net-mvc - 使用 AutoMapper 对 Controller 进行单元测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16446130/

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