我正在测试什么。
这是一个身份服务器项目,用于登录联合网关。 我不控制这个网关,并且他们没有将正确的声明返回给我,我需要验证用户登录。 我希望能够测试我是否可以处理这些错误。
例如,缺少电子邮件声明,否则我无法登录用户。
我创建了一个测试,用于测试缺少电子邮件声明返回错误。(工作正常)
现在我正试图测试事情的另一面。 如果声明确实存在,则应返回与返回的声明匹配的用户。
我们正在测试的方法
public static async Task<(ApplicationUser user, string provider, string providerUserUserName, IEnumerable<Claim> claims, string message)> FindUserFromExternalProvider(AuthenticateResult result, UserManager<ApplicationUser> userManager, ILogger<SegesExternalController> logger)
{
var externalUser = result.Principal;
// try to determine the unique id of the external user (issued by the provider)
var eMailClaim = externalUser.FindFirst(SegesSettingsConstants.SegesEmailClaimName);
if(eMailClaim == null) return (null, null, null, null, $"{SegesSettingsConstants.SegesEmailClaimName} claim not found.");
// remove the user id claim so we don't include it as an extra claim if/when we provision the user
var claims = externalUser.Claims.ToList();
claims.LogSegesClaims(logger);
claims.Remove(eMailClaim);
// Should we remove more claims
var provider = result.Properties.Items["scheme"];
var providerUserUserName = eMailClaim.Value;
var user = await userManager.FindByEmailAsync(providerUserUserName); // Test Breaks here
return (user, provider, providerUserUserName, claims, null);
}
测试
[Fact]
public async void Federated_login_with_email_claim_return_no_error()
{
// Arrange
var principal = new ClaimsPrincipal();
principal.AddIdentity(new ClaimsIdentity(
new Claim[] {
new Claim("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name", "Testbruger til André"),
new Claim("http://schemas.microsoft.com/ws/2008/06/identity/claims/windowsaccountname", @"PRODSalg43"),
new Claim("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/postalcode", "8200"),
new Claim("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/locality", "Aarhus N"),
new Claim("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress", "test@email.com"),
},
"FakeScheme"));
var authenticateResult = AuthenticateResult.Success(new AuthenticationTicket(principal, new AuthenticationProperties() { Items = { { "scheme", "fed" } } }, "FakeScheme"));
var exprectUser = new ApplicationUser()
{
UserName = "test@email.com",
NormalizedUserName = "TEST@EMAIL.COM",
NormalizedEmail = "TEST@EMAIL.COM",
Email = "test@email.com",
Id = 123,
EmailConfirmed = true
};
var mockEmailStore = new Mock<IUserEmailStore<ApplicationUser>>();
var mockQueryableUserStore = new Mock<IQueryableUserStore<ApplicationUser>>();
var mockUserStore = new Mock<IUserStore<ApplicationUser>>();
mockUserStore.Setup(x => x.FindByIdAsync(exprectUser.Id.ToString(), CancellationToken.None)).ReturnsAsync(exprectUser);
var userManager = new UserManager<ApplicationUser>(mockUserStore.Object, null, null, null, null, null, null, null, null);
var logger = new Logger<ExternalController>(new LoggerFactory());
// Act
var (user, provider, providerUserUserName, claims, errorMessage) = await AuthorizationHelpers.FindUserFromExternalProvider(authenticateResult, userManager, logger);
// Assert
user.ShouldNotBeNull();
}
上面的问题。
我正在尝试为我的单元测试修改用户管理器
var exprectUser = new ApplicationUser()
{
UserName = "test@email.com",
NormalizedUserName = "TEST@EMAIL.COM",
NormalizedEmail = "TEST@EMAIL.COM",
Email = "test@email.com",
Id = 123,
EmailConfirmed = true
};
var mockUserStore = new Mock<IUserStore<ApplicationUser>>();
mockUserStore.Setup(x => x.FindByIdAsync(exprectUser.Id.ToString(), CancellationToken.None)).ReturnsAsync(exprectUser);
var userManager = new UserManager<ApplicationUser>(mockUserStore.Object, null, null, null, null, null, null, null, null);
但是,当我正在测试的方法尝试找到用户时。
var findUser = await userManager.FindByEmailAsync("test@test.com");
它抛出一个错误
消息:System.NotSupportedException : Store 不实现 IUserEmailStore。
如何在我的最小起订量用户管理器中实现 IUserEmailStore?
我的单元测试项目确实包含最新的实体框架包。
尝试另一种方式。
var founduser = userManager.Users.FirstOrDefault(e => e.Email.Equals("test@test.com", StringComparison.InvariantCultureIgnoreCase));
结果在
System.NotSupportedException : Store 不实现 IQueryableUserStore。
我想我一定是错了。
更新自评论
好的,我可以对 IUserEmailStore 进行最小起订量,但我不确定我应该如何处理它
var mockEmailStore = new Mock<IUserEmailStore<ApplicationUser>>();
我设法创建了一个完整的最小起订量用户管理器,让我可以搜索电子邮件
public class MoqUserManager : UserManager<ApplicationUser>
{
public MoqUserManager(IUserStore<ApplicationUser> userStore) : base(userStore,
new Mock<IOptions<IdentityOptions>>().Object,
new Mock<IPasswordHasher<ApplicationUser>>().Object,
new IUserValidator<ApplicationUser>[0],
new IPasswordValidator<ApplicationUser>[0],
new Mock<ILookupNormalizer>().Object,
new Mock<IdentityErrorDescriber>().Object,
new Mock<IServiceProvider>().Object,
new Mock<ILogger<UserManager<ApplicationUser>>>().Object)
{ }
public override Task<ApplicationUser> FindByEmailAsync(string email)
{
return Task.FromResult(new ApplicationUser { Email = email });
}
}
这给了我
var mockUserStore = new Mock<IUserStore<ApplicationUser>>();
mockUserStore.Setup(x => x.FindByIdAsync(exprectUser.Id.ToString(), CancellationToken.None)).ReturnsAsync(exprectUser);
var userManager = new FakeUserManager(mockUserStore.Object);
因此,现在我可以验证是否从我的身份服务器返回了与联合登录用户匹配的正确用户。
好的,您对问题所在的最新问题
var userManager = new UserManager<ApplicationUser>(mockUserStore.Object, null, null, null, null, null, null, null, null);
这不是在创建模拟,而是创建UserManager<T>
的实际实例。
你将不得不做
var userManagerMock = new Mock<UserManager<ApplicationUser>>(mockUserStore.Object, null, null, null, null, null, null, null, null);
然后进行设置
userManagerMock.Setup(um => um.FindByEmailAsync("test@email.com)).Returns(exprectUser)
并将userManagerMock.Object
传递给您的
var (user, provider, providerUserUserName, claims, errorMessage) = await AuthorizationHelpers.FindUserFromExternalProvider(authenticateResult, userManagerMock.Object, logger);
模拟时,你永远不想调用外部依赖项的new
,而是模拟它,因为这样你就无法针对特定测试更改它的行为。UserManager<T>
应将所有或大多数公共属性作为虚拟属性,以便您可以覆盖它们。