I am doing a Unit Test for one of my method in my Controller, using Moq and Nunit Framework. I am trying hard to understand the concept of Mocking repositories & other objects, but not making much success.
I have a method which doesn't allow the user to delete a student who has a pending balance in his/her account. The logic for the method is in my StudentController, in POST method, and I am also using repository and Dependency Injection (not sure if that is causing an issue). When I run my Unit test, sometimes it goes to my GET Delete() method and if it goes to the POST methodI get an error saying "Object reference not set to an instance of an object" for the line of code saying this if (s.PaymentDue > 0)?
StudentController
public class StudentController : Controller
{
private IStudentRepository studentRepository;
public StudentController()
{
this.studentRepository = new StudentRepository(new SchoolContext());
}
public StudentController(IStudentRepository studentRepository)
{
this.studentRepository = studentRepository;
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Delete(int id)
{
//studentRepository.DeleteStudent(id);
Student s = studentRepository.GetStudentByID(id);
var paymentDue = false;
if (s.PaymentDue > 0)
{
paymentDue = true;
ViewBag.ErrorMessage = "Cannot delete student. Student has overdue payment. Need to CLEAR payment before deletion!";
return View(s);
}
if (!paymentDue)
{
try
{
Student student = studentRepository.GetStudentByID(id);
studentRepository.DeleteStudent(id);
studentRepository.Save();
}
catch (DataException /* dex */)
{
//Log the error (uncomment dex variable name after DataException and add a line here to write a log.
return RedirectToAction("Delete", new { id = id, saveChangesError = true });
}
}
//return View(s);
return RedirectToAction("Index");
}
Unit Test Method
private int studentID;
[TestMethod]
public void StudentDeleteTest()
{
//create list of Students to return
var listOfStudents = new List<Student>();
listOfStudents.Add(new Student
{
LastName = "Abc",
FirstMidName = "Abcd",
EnrollmentDate = Convert.ToDateTime("11/23/2010"),
PaymentDue = 20
});
Mock<IStudentRepository> mockStudentRepository = new Mock<IStudentRepository>();
mockStudentRepository.Setup(x => x.GetStudents()).Returns(listOfStudents);
var student = new StudentController(mockStudentRepository.Object);
//Act
student.Delete(studentID);
////Assert
mockStudentRepository.Verify(x => x.DeleteStudent(studentID), Times.AtLeastOnce());
}

NullReferenceExceptionis? Can you debug and figure out what object is null?GetStudentByID. You've only mockedGetStudents.