使用AutoMapper的Controller上的单元测试

Ste*_*ven 15 asp.net-mvc moq xunit automapper

我正在尝试对使用AutoMapping的UpdateUser控制器进行单元测试.这是控制器的代码

UpdateUserController

    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);
    }
Run Code Online (Sandbox Code Playgroud)

这是我的单元测试 UpdateUserControllerTest

[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);
    }
Run Code Online (Sandbox Code Playgroud)

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

Ada*_*ger 18

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

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

  • 嗨亚当,谢谢你的回应.我设法通过调用我在测试构造函数中的global.asax中创建的AutoMapperConfiguration.Configure()方法来修复它. (2认同)
  • 在[TestFixtureSetUp]方法中使用AutoMapperConfiguration.Configure(),我认为这是最好的方法. (2认同)