grozdeto
grozdeto

Reputation: 1379

How to mock IEnumerable in AddClaimsAsync method in order to run a unit test

I need to Mock the AddClaimsAsync() method which is this one here. I have an issue with the IEnumerable. After reading I found out that if I mock an object and then add it to a Collection it should work.:

public async Task<IdentityResult> AddClaimsAsync(IntentUser user, IEnumerable<Claim> claims)
{
    return await this.userManager.AddClaimsAsync(user, claims);
}

Here is the test:

var itemMock = new Mock<Claim>();
var items = new List<Claim> {itemMock.Object};
userManagerWrapperMock.Setup(u => u.AddClaimsAsync(admin, items)).ReturnsAsync(admin, new[]
{
    new Claim(JwtClaimTypes.Name, dto.FirstName),
    new Claim(JwtClaimTypes.GivenName, dto.FirstName),
    new Claim(JwtClaimTypes.FamilyName, dto.FamilyName),
    new Claim(JwtClaimTypes.Email, dto.Email),
    new Claim(JwtClaimTypes.EmailVerified, dto.EmailConfirmed.ToString(), ClaimValueTypes.Boolean)
});

This is the method in the Controller that needs to be mocked:

await userManagerWrapper.AddClaimsAsync(usr, new[]
{
    new Claim(JwtClaimTypes.Name, userDto.FirstName),
    new Claim(JwtClaimTypes.GivenName, userDto.FirstName),
    new Claim(JwtClaimTypes.FamilyName, userDto.FamilyName),
    new Claim(JwtClaimTypes.Email, user.Email),
    new Claim(JwtClaimTypes.EmailVerified, user.EmailConfirmed.ToString(), ClaimValueTypes.Boolean)
});

The error I get is:

'ISetup<IUserManagerWrapper, Task<IdentityResult>>' does not contain a definition for 'ReturnsAsync' and the best extension method overload 'ReturnsExtensions.ReturnsAsync<IUserManagerWrapper, IntentUser>(IReturns<IUserManagerWrapper, ValueTask<IntentUser>>, IntentUser, TimeSpan)' requires a receiver of type 'IReturns<IUserManagerWrapper, ValueTask<IntentUser>>'

Upvotes: 0

Views: 651

Answers (1)

grozdeto
grozdeto

Reputation: 1379

I did not need to return anything, it was a void method.

Also I did not need to Mock anything. Simply this works.

        userManagerWrapperMock.Setup(u => u.AddClaimsAsync(admin, new[]
        {
            new Claim(JwtClaimTypes.Name, dto.FirstName),
            new Claim(JwtClaimTypes.GivenName, dto.FirstName),
            new Claim(JwtClaimTypes.FamilyName, dto.FamilyName),
            new Claim(JwtClaimTypes.Email, dto.Email),
            new Claim(JwtClaimTypes.EmailVerified, dto.EmailConfirmed.ToString(), ClaimValueTypes.Boolean)
        }));

Upvotes: 1

Related Questions