jeudi 27 août 2015

Testing a MVC Controller fails with NULL reference exception

Below is the setup that I am trying to test.

The controller:

public ActionResult UpsertStudent(StudentModel studentModel)
{
    try
    {

        if (!CheckStudentUpdateForEdit(studentModel))
        {

            return Json(new { result = STUDENT_EXISTS });

        }
    // remaining code removed for brevity 
}

private bool CheckStudentUpdateForEdit(StudentModel studentModel)
{
    var returnVal = true;

    var existingStudent = _updateStudentManager.GetStudentInfo(studentModel.Id);

    if (existingStudent.StudentType == "Day Scholar")
    {
        returnVal = true;
    }
    else
    {
        returnVal = false;
    }

    return returnVal;
}

The Test method:

public void AllowStudentUpdates_Success()
{
    var studentModel = new StudentModel()
    {
        StudentName = "Joe",
        Id = "123",
        StudentType = "Day Scholar"
    };

    var studentToAdd = new Student()
    {
        Id = "123",
        Name = "Joe",
        StartDate = DateTime.UtcNow.ToShortDateString(),
        StudentType = "Day Scholar",
        EndDate = "08/10/2016"
    };

    _studentRulesHelper.Setup(x => x.GetStudentRule(studentModel, true)).Returns(studentToAdd);
    _productRulesHelper.Setup(x => x.ReturnStudentRule(studentModel, true)).Returns(studentToAdd);

    var res = _controller.UpsertDoc(studentModel) as JsonResult;
    if (res != null) Assert.AreEqual("{ result = True }", res.Data.ToString());
}

When it hits the UpsertDoc call, it goes to the actual call in the controller and tries to execute

CheckStudentUpdateForEdit()

The

GetStudentInfo()

tries to get an object from the db and returns a null object as there is no student with the id that's passed from the test method. The test then fails with Null Reference exception.

Now the system under test is not supposed to hit the db. I don't know why this is doing the other way!

Anyone else writing this test will also try to pass a dummy object which is bound to fail at GetStudentInfo() the way the test is setup now.

What do I do to make this work?

Aucun commentaire:

Enregistrer un commentaire