如何为控制器使用automapper编写单元测试?

时间:2015-02-19 11:36:41

标签: asp.net-mvc unit-testing nunit automapper

我试图为控制器编写单元测试以测试方法返回所有用户。但我很困惑如何用automapper编写单元测试

控制器:

private readonly IUserService _userService;

public UserController(IUserService userService)
{
  this._userService = userService;
}

public ActionResult List()
{
  var users = _userService.GetAllUsers().ToList();
  var viewModel = Mapper.Map<List<UserViewModel>>(users);
  return View(viewModel);
}

控制器测试:

    private Mock<IUserService> _userServiceMock;
    UserController objUserController;
    List<UserViewModel> listUser;

    [SetUp]
    public void Initialize()
    {
        _userServiceMock = new Mock<IUserService>();
        objUserController = new UserController(_userServiceMock.Object);
        listUser = new List<UserViewModel>()
        {
            new UserViewModel() {Id = 1, Active = true, Password = "123456", UserName = "hercules"},
            new UserViewModel() {Id = 2, Active = false, Password = "1234567", UserName = "alibaba"},
            new UserViewModel() {Id = 3, Active = true, Password = "12345678", UserName = "robinhood"},
        };
    }

    [Test]
    public void Index_Returns_AllUser()
    {
      // How do I here ???
    }

4 个答案:

答案 0 :(得分:6)

像在MVC项目中一样配置automapper:

[SetUp]
public void Initialize()
{
    ....
    AutoMapperConfiguration.Configure();
}

AutoMapperConfiguration是一个公共静态类,如:

public class AutoMapperConfiguration
{

    /// <summary>
    /// Maps between VIEWMODEL and MODEL
    /// </summary>
    public static void Configure()
    {
        //maps here
         Mapper.CreateMap..
    }
}

答案 1 :(得分:1)

您可以使用接口为automapper创建包装类。例如:

public interface IMapperWrapper
{
     object Map(object source, Type sourceType, Type destinationType);
}

然后你在测试中需要做的只是嘲笑你的地图。

automapperWrapperMock.Setup(x => x.Map, type, type);

答案 2 :(得分:1)

你正在尝试编写一个几乎没有价值的测试。不要写这个测试。使用真正的IUserService并使用真正的AutoMapper并对ViewResult进行断言。

我永远不会对这段代码进行单元测试。

但如果您完全不愿意编写此单元测试,请不要模拟AutoMapper。模拟IUserService。

UserController objUserController;
List<User> listUser;

[SetUp]
public void Initialize()
{
    var userServiceMock = new Mock<IUserService>();
    listUser = new List<User>()
    {
        new User() {Id = 1, Active = true, Password = "123456", UserName = "hercules"},
        new User() {Id = 2, Active = false, Password = "1234567", UserName = "alibaba"},
        new User() {Id = 3, Active = true, Password = "12345678", UserName = "robinhood"},
    };
    userServiceMock.Setup(framework => framework.GetAllUsers())
  .Returns(listUser);

    objUserController = new UserController(_userServiceMock.Object);
}

[Test]
public void Index_Returns_AllUser()
{
    var result = objUserController.List();

    var viewResult = result as ViewResult;

    viewResult.ShouldNotBe(null);
    var model = viewResult.Model as List<UserListModel>;
    model.ShouldNotBe(null);

    model.Count.ShouldBe(3); // Don't do more than this
}

答案 3 :(得分:0)

只需设置控制器调用Automapper配置,该控制器的所有测试都将正常运行。

next()