How do i mock UserManager and RoleManager for unit test

前端 未结 1 985
悲&欢浪女
悲&欢浪女 2021-02-09 02:31

I have mocked abstract class to test concrete method of a class as following.

var mock = new Mock();
mock.CallBase = true;
var ta = moc         


        
相关标签:
1条回答
  • 2021-02-09 03:14

    Not sure why you're implementing TestUserManager and not just mocking it. Lat's say we have following code in controller:

    var owinContext = Request.GetOwinContext();
    var userManager = owinContext.GetUserManager<ApplicationUserManager>();
    var applicationUser = userManager.FindById("testId");
    

    You can inject mock user store this way:

    var owinMock = new Mock<IOwinContext>();
    
    var userStoreMock = new Mock<IUserStore<ApplicationUser>>();
    userStoreMock.Setup(s => s.FindByIdAsync("testId")).ReturnsAsync(new ApplicationUser
    {
        Id = "testId",
        Email = "test@email.com"
    });
    var applicationUserManager = new ApplicationUserManager(userStoreMock.Object);
    
    owinMock.Setup(o => o.Get<ApplicationUserManager>(It.IsAny<string>())).Returns(applicationUserManager);
    
    ta.Request.SetOwinContext(owinMock.Object);
    
    0 讨论(0)
提交回复
热议问题