我正在爲我的控制器中的一個方法使用Moq和Nunit框架進行單元測試。我正在努力理解其他對象的嘲笑庫的概念,但沒有取得太大的成功。System.NullReferenceException - .Net(MVC)模擬單元測試
我有一種方法,不允許用戶刪除他/她帳戶中有未結餘額的學生。該方法的邏輯是在我的StudentController中,在POST方法中,我也使用存儲庫和依賴注入(不確定是否導致問題)。當我運行我的單元測試時,有時會轉到我的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'是什麼嗎?你能調試並找出什麼對象是空的? – mason
你能調試並告訴我們你得到的錯誤是哪一行嗎? – Rinktacular
@Rinktacular他已經告訴我們錯誤來自哪裏。 – mason