Moq usermanager缺少IUserEmailStore

时间:2019-04-10 10:23:06

标签: c# asp.net-core asp.net-identity moq xunit

我正在测试什么。

这是一个身份服务器项目,具有登录到联合网关的权限。我无法控制此网关,并且遇到问题,他们没有向我退回我需要验证用户登录名的正确声明。我希望能够测试我可以处理这些错误。

例如,缺少电子邮件声明,但我无法登录用户。

我创建了一个测试,用于测试缺少电子邮件声明的返回错误。(工作正常)

现在,我正在尝试测试事物的另一面。如果索赔确实存在,则应该返回与返回的索赔匹配的用户。

我们正在测试的方法

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", @"PROD\Salg43"),
                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:存储未实现IUserEmailStore。

如何在Moq用户管理器中实现IUserEmailStore?

我的单元测试项目确实包含最新的EntityFramework软件包。

尝试另一种方式。

var founduser = userManager.Users.FirstOrDefault(e => e.Email.Equals("test@test.com", StringComparison.InvariantCultureIgnoreCase));

结果

  

System.NotSupportedException:存储未实现IQueryableUserStore。

我想我一定要错这个错。

根据评论更新

好的,我可以起订IUserEmailStore,但是我不确定该怎么做

var mockEmailStore = new Mock<IUserEmailStore<ApplicationUser>>();

2 个答案:

答案 0 :(得分:1)

我设法创建了一个完整的Moq用户管理器,使我可以在电子邮件上进行搜索

 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);

现在,我可以验证是否从身份服务器返回了与联合登录用户匹配的正确用户。

答案 1 :(得分:1)

好的,问题出在

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>应该具有所有或大多数公共属性作为虚拟属性,因此您可以覆盖它们。