public class AccountControllerTest
{
private IMapper _mapper;
private UserManager<User> userManager;
private SignInManager<User> _signInManager;
[TestMethod]
public void AccountController_Register_UserRegistered()
{
var accountController = new AccountController(_mapper,userManager,_signInManager);
var registerViewModel = new UserRegistrationModel
{
Email = "H@o2.pl",
Password = "Hej123@",
FirstName = "Hania",
LastName ="Kowalska"
};
var result = accountController.Register(registerViewModel).Result;
Assert.IsTrue(result is RedirectToRouteResult);
Assert.IsTrue(accountController.ModelState.All(kvp => kvp.Key != ""));
}
И мой AccountController.cs:
public class AccountController : Controller
{
private readonly IMapper _mapper;
private readonly UserManager<User> _userManager;
private readonly SignInManager<User> _signInManager;
public AccountController(IMapper mapper, UserManager<User> userManager, SignInManager<User> signInManager)
{
_mapper = mapper;
_userManager = userManager;
_signInManager = signInManager;
}
[HttpGet]
public IActionResult Register()
{
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Register(UserRegistrationModel userModel)
{
if (!ModelState.IsValid)
{
return View(userModel);
}
var user = _mapper.Map<User>(userModel);
var result = await _userManager.CreateAsync(user, userModel.Password);
if (!result.Succeeded)
{
foreach (var error in result.Errors)
{
ModelState.TryAddModelError(error.Code, error.Description);
}
return View(userModel);
}
await _userManager.AddToRoleAsync(user, "Visitor");
return RedirectToAction(nameof(HomeController.Index), "Home");
}
У меня в строке AccountController появляется ошибка при отладке теста:
var user = _mapper.Map<User>(userModel);
Ошибка: (Ссылка на объект не установлена к экземпляру объекта.)