Home > other >  c# UnitTest Mocking Setup of a class with GUID properties during each instance
c# UnitTest Mocking Setup of a class with GUID properties during each instance

Time:10-09

I'm trying to unit test some class mapping within a service that uses UserManager<AppUser>

I've hit a bump when trying to mock the CreateUserAsync method of my UserManager

mockUserManager.Setup(x => x.CreateAsync(_newUser, PASSWORD))
   .ReturnsAsync(IdentityResult.Success);

Where my new user is established with very minimal info:

_newUser = new AppUser { UserName = "[email protected]", Email = "[email protected]" };

The problem is, because the AppUser (derived from IdentityUser) has a bunch of other properties populated during construction (e.g. concurrenct / security stamp, Id) as GUIDS there's no way my Mock will ever match the implementation when the user is created in the service!

Is there any way I can use the mockUserManager.Setup() method to tell it to compare only specific properties??

I thought I may be able to use the It.Any() method but then figured that's just for a range of stuff...

CodePudding user response:

Instead of using a specific value, you can tell Moq to accept any value by using something like It.IsAny<string> or It.IsAny<AppUser>. So your mock would become:

mockUserManager
    .Setup(x => x.CreateAsync(It.IsAny<AppUser>, It.IsAny<string>))
    .ReturnsAsync(IdentityResult.Success);

This method will accept any user object and any password too.

  •  Tags:  
  • c#
  • Related