0
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 != ""));
    }

And my 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");
    }

I have the error on line in AccountController when I Debug Test :

var user = _mapper.Map<User>(userModel);

Error:(Object reference not set to an instance of an object.)

Mike G
  • 4,022
  • 9
  • 41
  • 63
xxx
  • 1
  • 1
  • You need to mock that call to _mapper to return the correct 'shape' of user. Have you used `Moq`? – Neil May 07 '20 at 16:09
  • Does this answer your question? [What is a NullReferenceException, and how do I fix it?](https://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it) – Mike G May 07 '20 at 16:24
  • I have never used Moq – xxx May 07 '20 at 17:01

0 Answers0