Working on .Net Core Project and created below service to share common methods across the pages.
namespace MyApp.Tests.Services
{
public class UserServiceTest
{
[Fact]
public async Task CreateUser_ShouldCreateUser()
{
var user = new UserResponse
{
Id = "111",
Email = "john@email.com",
FirstName = "John",
LastName = "Doe",
CompanyName = "SomeCompany",
PhoneNumber = "9123456789"
};
var appUser = new ApplicationUser
{
UserName = user.Email,
Email = user.Email,
FirstName = user.FirstName,
LastName = user.LastName,
CompanyName = user.CompanyName,
PhoneNumber = user.PhoneNumber
};
var logger = Mock.Of<ILogger<UserService>>();
var mockUserStore = new Mock<IUserStore<ApplicationUser>>();
mockUserStore
.Setup(x => x.CreateAsync(appUser, CancellationToken.None))
.ReturnsAsync(IdentityResult.Success).Verifiable();
// Tried this one as well but still getting null instead of IdentityResult
// mockUserStore
// .Setup(x => x.CreateAsync(appUser, CancellationToken.None))
// .ReturnsAsync(new IdentityResultMock(true));
var userManager = new UserManager<ApplicationUser>(mockUserStore.Object, null, null, null, null, null, null, null, null);
var _userService = new UserService(userManager, logger);
var result = await _userService.CreateUserInApp(user);
Assert.True(result.Succeeded);
}
}
public class IdentityResultMock : IdentityResult
{
public IdentityResultMock(bool succeeded) {
base.Succeeded = succeeded;
}
}
}
Also wrote the Unit Test case for this service like below to test the UserService
namespace MyApp.Tests.Services
{
public class UserServiceTest
{
[Fact]
public async Task CreateUser_ShouldCreateUser()
{
var user = new UserResponse
{
Id = "111",
Email = "john@email.com",
FirstName = "John",
LastName = "Doe",
CompanyName = "SomeCompany",
PhoneNumber = "9123456789"
};
var appUser = new ApplicationUser
{
UserName = user.Email,
Email = user.Email,
FirstName = user.FirstName,
LastName = user.LastName,
CompanyName = user.CompanyName,
PhoneNumber = user.PhoneNumber
};
var logger = Mock.Of<ILogger<UserService>>();
var mockUserStore = new Mock<IUserStore<ApplicationUser>>();
mockUserStore
.Setup(x => x.CreateAsync(appUser, CancellationToken.None))
.ReturnsAsync(IdentityResult.Success).Verifiable(); ;
var userManager = new UserManager<ApplicationUser>(mockUserStore.Object, null, null, null, null, null, null, null, null);
var _userService = new UserService(userManager, logger);
var result = await _userService.CreateUserInApp(user);
Assert.True(result.Succeeded);
}
}
}
While running test in user service at
var createResult = await _userManager.CreateAsync(appUser);
createResult I am getting null due to this Test Case is failing and getting null reference exception. If I could return IdentityResult from mock CreateAsync setup then it will pass but not sure what wrong I am doing. Also Can not create object of IdentityResult because 'Succeeded' is protected and can not assign value explicitly. Please help. Thanks :)