Moq 및 Nunit Framework를 사용하여 내 컨트롤러에서 내 메서드에 대한 단위 테스트를 수행하고 있습니다. 저는 모킹 저장소 & 다른 객체의 개념을 이해하려고 열심히 노력하고 있지만 많은 성공을 이루지 못하고 있습니다.System.NullReferenceException-.Net (MVC) 모의 단위 테스트
나는 계좌 잔고가있는 학생을 삭제할 수없는 방법이 있습니다. 메서드에 대한 논리는 Student 메서드의 POST 메서드에 있으며 저장소 및 Dependency Injection (문제가 발생했는지 확실하지 않음)도 사용하고 있습니다. 단위 테스트를 실행할 때 가끔 GET Delete()
메서드로 이동하고 POST method
으로가는 경우이 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");
}
단위 시험 방법
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());
}
'NullReferenceException'은 무엇인지 알고 계십니까? 디버그하고 어떤 객체가 null인지 파악할 수 있습니까? – mason
디버깅하여 오류가 발생한 행을 알려줄 수 있습니까? – Rinktacular
@Rinktacular 그는 오류가 발생한 줄을 이미 말했습니다. – mason