'xUnit test error System.NullReferenceException when creating a viewModel instance to test a controller

I want to test the Create(ClienteViewModel cliente), and I'm having difficulty creating an instance of it. I have tried to mock the viewModel, but returns me a different error.

The code of the test I'm getting the error from:


        [Fact]
        public void Post_Create_Client()
        {
            var controller = new PoollGest.Controllers.ClientesController(_context);
            // Arrange
          /*  var mockRepo = new Mock<ClienteViewModel>();
            mockRepo.SetupProperty(m => m.Nome, "nome");
            mockRepo.SetupProperty(m => m.Desconto, 0);*/
          ClienteViewModel viewModel = new ClienteViewModel { 
                  Nome ="nome",
                  Desconto = 0,
          };

            // Act
            var result =  controller.Create(viewModel);

            // Assert
            var viewResult = Assert.IsType<ViewResult>(result);
            var model = Assert.IsType<ClienteViewModel>(viewResult.ViewData.Model);
            Assert.Equal("nome", model.Nome);
            Assert.Equal(0, model.Desconto);
        }
    }

Controller, the Create Action I'm testing:

 [HttpPost]
        [ValidateAntiForgeryToken]
        public IActionResult Create(ClienteViewModel cliente)
        {
            if (ModelState.IsValid)
            {
                Cliente c = new Cliente
                {
                    Nome = cliente.Nome,
                    Desconto = cliente.Desconto,
                    DataNascimento = cliente.DataNascimento,
                    NIF = cliente.NIF
                };
                _context.Add(c);
                _context.SaveChanges();
                TempData["success"] = true;
                TempData["msg"] = "Cliente adicionado com sucesso.";
                return RedirectToAction(nameof(Index));
            }
            TempData["error"] = true;
            TempData["msg"] = "Ocorreu um problema.";
            return View(cliente);
        }

Error's I'm getting:

NullReferenceException: NullReferenceException error

If I mock the viewModel, change the call to Create(mockRepo.Object), gives me another error mockError

Before doing this test the VerifyModelState worked verifyModelState



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source