我有ChangePassword
方法,我UserManager.ChangePasswordAsync(userId, oldPassword, newPassword);
更改密码'。
问题:上面一行会出现以下错误。
System.NotSupportedException:Store未实现 IUserPasswordStore。
ChangePassword方法代码行
IdentityResult result = await UserManager.ChangePasswordAsync(userId, oldPassword, newPassword);
单元测试
var mock = new Mock<MyController>();
mock.CallBase = true;
var obj = mock.Object;
obj.ControllerContext = new HttpControllerContext { Request = new HttpRequestMessage() };
obj.Request.SetOwinContext(CommonCodeHelper.mockOwinContext());
IPrincipal user = GetPrincipal();
obj.ControllerContext.RequestContext.Principal = user;
var result = await obj.ChangePassword(dto);
IOwinContext模拟代码
public static IOwinContext mockOwinContext()
{
var owinMock = new Mock<IOwinContext>();
owinMock.Setup(o => o.Authentication.User).Returns(new ClaimsPrincipal());
owinMock.Setup(o => o.Request).Returns(new Mock<OwinRequest>().Object);
owinMock.Setup(o => o.Response).Returns(new Mock<OwinResponse>().Object);
owinMock.Setup(o => o.Environment).Returns(new Dictionary<string, object> { { "key1", 123 } });
var traceMock = new Mock<TextWriter>();
owinMock.Setup(o => o.TraceOutput).Returns(traceMock.Object);
var userStoreMock = new Mock<IUserStore<ApplicationUser>>();
userStoreMock.Setup(s => s.FindByIdAsync("User1@test.com")).ReturnsAsync(new ApplicationUser
{
Id = "User1@test.com",
FirstName = "Test",
LastName = "User1",
Email = "User1@test.com",
UserName = "User1@test.com",
});
var appManager = new ApplicationUserManager(userStoreMock.Object);
owinMock.Setup(o => o.Get<ApplicationUserManager>(It.IsAny<string>())).Returns(appManager );
return owinMock.Object;
}
在收到上述错误后,我尝试使用以下代码行模拟IUserPassword
内的IOwinContext code block (above method)
var passwordManager = userStoreMock.As<IUserPasswordStore<ApplicationUser>>();
我认为以上IUserPassword的模拟代码是不正确的,因为现在它给出了异常
System.InvalidOperationException:找不到UserId。
如何模拟IUserPasswordStore<TUser>
?