Moq在mvc中抛出System.NullReferenceException

时间:2014-09-17 16:25:36

标签: asp.net-mvc nunit moq

我有一个客户控制器

     //httpget
     public ActionResult Create()
    {
        return View();
    }

    //httppost
    public ActionResult Create(Customer customer)
    {
        if (ModelState.IsValid)
        {
            db.Customers.Add(customer);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        return View(customer);
    }

我创建了一个单元测试

      [Test]
      public void Should_Return_To_Index_Page_After_Saving_A_Valid_Customer()
    {
        var mockContext = new Mock<DbContext>();
        var mockCustomer = new Mock<Customer>();
        var sut = new CustomerController(mockContext.Object);

        var result = sut.Create(mockCustomer.Object) as RedirectToRouteResult;
        Assert.That(result.RouteValues["action"], Is.EqualTo("Index"));
    }

但它总是抛出一个异常&#34;类型&#39; System.NullReferenceException&#39;的例外。发生&#34;在Create方法中的db.Customers.Add(customer)。谁能解释一下我在哪里做错了?

我对MVC nunit测试有点新鲜

2 个答案:

答案 0 :(得分:0)

您的Mock<DbContext>Customers属性返回null。

你可能需要这样做:

var mockCustomers = new Mock<IList<Customer>>(); // or whatever type it needs to be
mockContext.Setup(x => x.Customers).Returns(mockCustomers.Object);

答案 1 :(得分:0)

在这种情况下,您不需要模拟Customer类和集合。在这种情况下,你应该嘲笑的唯一依赖是DbContext。

[Test]
public void Should_Return_To_Index_Page_After_Saving_A_Valid_Customer()
{
    var mockContext = new Mock<DbContext>();
    mockContext.Setup(x => x.Customers).Returns(new List<Customer>());

    var sut = new CustomerController(mockContext.Object);

    var result = sut.Create(new Customer()) as RedirectToRouteResult;
    Assert.That(result.RouteValues["action"], Is.EqualTo("Index"));
}