Here is the scenario- I have users that I want to seed from a controller. I have configured default user creds in secret.json file, configured them in services and retrieve them in controller using IOption where T is the DefaultUserCred.cs Now, I want to create xunit test for this. What is the way to achieve this without configuring IService in Test unit.
here's code sample ---
private readonly ApplicationDbContext _context;
private readonly RoleManager<IdentityRole> _roleManager;
private readonly UserManager<ApplicationUser> _userManager;
private readonly IWebHostEnvironment _env;
private readonly DefaultUserOptions _options;
public SeedController(
ApplicationDbContext context,
RoleManager<IdentityRole> roleManager,
UserManager<ApplicationUser> userManager,
IWebHostEnvironment env,
IOptions<DefaultUserOptions> options
)
{
_context = context;
_roleManager = roleManager;
_userManager = userManager;
_env = env;
_options = options.Value;
}
public async Task<ActionResult> CreateDefaultUsers()
{
string role_RegisteredUser = "RegisteredUser";
string role_Administrator = "Administrator";
if (await _roleManager.FindByNameAsync(role_RegisteredUser) ==
null)
await _roleManager.CreateAsync(new
IdentityRole(role_RegisteredUser));
if (await _roleManager.FindByNameAsync(role_Administrator) ==
null)
await _roleManager.CreateAsync(new
IdentityRole(role_Administrator));
var addedUserList = new List<ApplicationUser>();
var email_Admin = _options.Admin_Email;
if (await _userManager.FindByNameAsync(email_Admin) == null)
{
var user_Admin = new ApplicationUser()
{
SecurityStamp = Guid.NewGuid().ToString(),
UserName = email_Admin,
Email = email_Admin,
};
await _userManager.CreateAsync(user_Admin, _options.Admin_Password);
await _userManager.AddToRoleAsync(user_Admin,
role_RegisteredUser);
await _userManager.AddToRoleAsync(user_Admin,
role_Administrator);
user_Admin.EmailConfirmed = true;
user_Admin.LockoutEnabled = false;
addedUserList.Add(user_Admin);
}
var email_User = _options.User_Email;
if (await _userManager.FindByNameAsync(email_User) == null)
{
var user_User = new ApplicationUser()
{
SecurityStamp = Guid.NewGuid().ToString(),
UserName = email_User,
Email = email_User
};
await _userManager.CreateAsync(user_User, _options.User_Password);
await _userManager.AddToRoleAsync(user_User,
role_RegisteredUser);
user_User.EmailConfirmed = true;
user_User.LockoutEnabled = false;
addedUserList.Add(user_User);
}
if (addedUserList.Count > 0)
await _context.SaveChangesAsync();
return new JsonResult(new
{
Count = addedUserList.Count,
Users = addedUserList
});
}
}
Thanks for help.