使用UserManager.FindById对单元测试控制器

时间:2016-12-11 17:26:38

标签: asp.net-mvc unit-testing moq

我是单位测试.net应用程序的新手,我很难想象这是一个非常简单的案例。

// GET: Entities
public ViewResult Index()
{
  _User = UserManager.FindById(User.Identity.GetUserId());
  return View(entityRepository.GetEntities(_User.entityId));         
}

我想测试是否输出了正确的视图,但无法通过用户线。在其他语言中,我只是模拟UserManager.FindById以始终返回一些预定义的对象,但我无法使其工作。

一直在尝试按照此处给出的方法example mocking the IUserStore ,但无法使用我的示例。为了模拟FindByNameAsync,他们使用了store.As

感谢任何建议。

我的尝试是遵循与上面链接中类似的方法。显然IUserPasswordStore是错误的界面,但我不知道如何找到正确的界面。

 var store = new Mock<IUserStore<ApplicationUser>>(MockBehavior.Strict);
 store.As<IUserPasswordStore<ApplicationUser>>()
      .Setup(x => x.FindById(It.IsAny<string>()))
      .Returns(ApplicationUser)null);   

 EntitiesController controller = new EntitiesController();
 var result = controller.Index() as ViewResult;
 Assert.AreEqual("Index", result.ViewName);

1 个答案:

答案 0 :(得分:0)

所以,感谢@Nkosi和@ haim770的指导,我想我有一个答案。它似乎仍然过于复杂,所以如果你知道如何简化,那么你会感兴趣。

首先需要编写更多可测试的代码,我安装了Unity并开始注入依赖项,允许我模拟它们。

通过的解决方案是:

Mock<IPrincipal> mockPrincipal;
string username = "test@test.com";

[TestInitialize]
public void TestInitialize()
{
    //Arrange                
    var identity = new GenericIdentity(username, "");
    var nameIdentifierClaim = new Claim(ClaimTypes.NameIdentifier, username);
    identity.AddClaim(nameIdentifierClaim);

    mockPrincipal = new Mock<IPrincipal>();
    mockPrincipal.Setup(x => x.Identity).Returns(identity);
    mockPrincipal.Setup(x => x.IsInRole(It.IsAny<string>())).Returns(true);
}

[TestMethod]
public void EntitiesIndexDisplaysTheDefaultView()
{
    var context = new Mock<HttpContextBase>(); 
    var principal = mockPrincipal.Object;
    context.Setup(x => x.User).Returns(principal);

    var userManagerMock = new Mock<IUserStore<ApplicationUser>>(MockBehavior.Strict);
    userManagerMock.As<IUserPasswordStore<ApplicationUser>>()
         .Setup(x => x.FindByIdAsync(It.IsAny<string>()))
         .ReturnsAsync(new ApplicationUser() { entityId = "id" });

    var entitiesRepositoryMock = new Mock<IEntityRepository>();
    entitiesRepositoryMock
        .Setup(x => x.GetEntities(It.IsAny<string>()))
        .Returns((IEnumerable<Entity>)new List<Entity>());


    EntitiesController controller = new EntitiesController(new UserManager<ApplicationUser>(userManagerMock.Object), 
                                                               entitiesRepositoryMock.Object);

    controller.ControllerContext = new ControllerContext(context.Object, new RouteData(), controller);
    var result = controller.Index() as ViewResult;
    Assert.AreEqual("", result.ViewName);           
}