【发布时间】:2017-02-15 14:31:03
【问题描述】:
我正在使用 Moq 和 Nunit 框架对我的控制器中的一种方法进行单元测试。我正在努力理解模拟存储库和其他对象的概念,但没有取得多大成功。
我有一种方法不允许用户删除其帐户中有未结余额的学生。该方法的逻辑在我的 StudentController 中,在 POST 方法中,并且我还在使用存储库和依赖注入(不确定这是否会导致问题)。当我运行我的单元测试时,有时它会转到我的GET Delete() 方法,如果它转到POST method,我会收到一条错误消息,指出“对象引用未设置为对象的实例”,因为代码行说这个@ 987654325@?
学生控制器
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是什么吗?你能调试并找出什么对象是空的吗? -
您能否调试并告诉我们您在哪一行得到错误?
-
@Rinktacular 他已经告诉我们错误来自哪一行。
-
s.PaymentDue 是可以为空的类型吗?是否必须指定 s.PaymentDue.Value?
-
你没有嘲笑
GetStudentByID。你只是嘲笑GetStudents。
标签: c# asp.net asp.net-mvc unit-testing moq