从模拟的应用程序用户管理器返回用户



我正在尝试模拟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为 null。 似乎this.userManager.Users没有返回我尝试在测试方法中设置的用户。

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

用户管理器公开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
}

查看快速入门文档以更熟悉模拟框架

相关内容

  • 没有找到相关文章

最新更新