从模拟的ApplicationUserManager.Users返回用户

时间:2017-06-16 17:31:47

标签: c# asp.net-mvc unit-testing asp.net-identity moq

我正在尝试模拟ApplicationUserManager.Users,以便我可以测试控制器方法。我的控制器是

public class ManageController : Controller
{
    private readonly ApplicationUserManager userManager;

    public ManagerController(ApplicationUserManager userManager)
    {
        this.userManager = userManager;
    }

    // The method being tested
    public ActionResult ListUsers()
    {
        // I want this to return my mocked user list
        var users = this.userManager.Users.ToList();

        // Do other stuff
    }
}

我的测试方法是

[TestMethod]
public void ListUsersGet_ShouldSucceed()
{
    var users = new List<ApplicationUser>
    {
        new ApplicationUser { Id = "1", FirstName = "Test", LastName = "User" }
    }.AsQueryable();
    Mock<DbSet<ApplicationUser>> dbSet = new Mock<DbSet<ApplicationUser>>();
    dbSet.As<IQueryable<ApplicationUser>>().Setup(e => e.ElementType).Returns(users.ElementType);
    dbSet.As<IQueryable<ApplicationUser>>().Setup(e => e.Expression).Returns(users.Expression);
    dbSet.As<IQueryable<ApplicationUser>>().Setup(e => e.GetEnumerator()).Returns(users.GetEnumerator());
    dbSet.As<IQueryable<ApplicationUser>>().Setup(e => e.Provider).Returns(users.Provider);

    Mock<MyContext> context = new Mock<MyContext>();
    context.Setup(e => e.Users).Returns(dbSet.Object);

    Mock<UserStore<ApplicationUser>> userStore = new Mock<UserStore<ApplicationUser>>(context.Object);

    var controller = new ManageController(new ApplicationUserManager(userStore.Object));

    var result = controller.ListUsers() as ViewResult;

    // Assert some stuff
}        

当我进入我的控制器方法时,我可以看到users为空。 this.userManager.Users似乎没有返回我尝试在我的测试方法中设置的用户。

如何让this.userManager.Users.ToList()返回我的测试用户?

1 个答案:

答案 0 :(得分:2)

用户管理器公开public virtual IQueryable<TUser> Users { get; }属性。模拟用户管理器依赖项并将其提供给控制器。

public void _ListUsersGet_ShouldSucceed() {
    // Arrange.
    var users = new List<ApplicationUser>
    {
        new ApplicationUser { Id = "1", FirstName = "Test", LastName = "User" }
    }.AsQueryable();

    //Only mocking this because we need it to initialize manager.
    var userStore = Mock.Of<IUserStore<ApplicationUser>>();

    var userManager = new Mock<ApplicationUserManager>(userStore);
    userManager.Setup(_ => _.Users).Returns(users);

    var controller = new ManageController(userManager.Object);

    // Act.
    var result = controller.ListUsers() as ViewResult;

    // Assert some stuff
}

检查Quick start documentation以更熟悉模拟框架