2013-10-10 36 views
-2

我正在通过史蒂夫桑德森的书Pro ASP.NET MVC框架和我有一个单元测试产生错误的问题。Asp.Net MVC教程单元测试 - 史蒂夫桑德森

在下面的例子中,它测试了Paginate。

[TestMethod] 
public void Can_Paginate() 
{ 

     Mock<IProductRepository> mock = new Mock<IProductRepository>(); 

     mock.Setup(m => m.Products).Returns(new Product[] { 
     new Product{ProductID=1,Name="P1"}, 
     new Product{ProductID=2,Name="P2"}, 
     new Product{ProductID=3,Name="P3"}, 
     new Product{ProductID=4,Name="P4"}, 
     new Product{ProductID=5,Name="P5"} 
     }.AsQueryable()); 

     ProductController controller = new ProductController(mock.Object);  
     controller.PageSize = 3; 

     IEnumerable<Product> result = (IEnumerable<Product>)controller.List(2).Model; 

     Product[] prodArray = result.ToArray(); 
     Assert.IsTrue(prodArray.Length == 2); 
     Assert.AreEqual(prodArray[0].Name, "P4"); 
     Assert.AreEqual(prodArray[0].Name, "P5"); 
} 

消息错误是:

试验方法UnitTestProject3.Peginate.Can_Peginate抛出异常: System.NullReferenceException。

有没有人遇到类似的问题或得到测试通过?

+2

它说哪一行? – ysrb

+1

您可以在控制器上发布List方法的代码? –

+1

你不会在书中学习编程,你可以通过理解你在做什么以及编译器告诉你什么来编程,你可以解释什么是NullReferenceException,以及如何调试和消除它们[这里](http://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-in-net-and-how-do-i-fix-it)。 – CodeCaster

回答

1

你做了几个错别字和需要更新这些行:

ProductListViewModel result = (ProductsListViewModel)controller.List(null, 2).Model; 

Assert.AreEqual(prodArray[1].Name, "P5"); 

在ProductsController类,本教程有您更新的ViewResult这样:

public ViewResult List(string category, int page = 1) 

该书然后陈述“我们已经改变了列表动作方法的签名,这将p避免编译我们现有的单元测试方法。要解决这个问题,在作为控制器的单元测试中,将null作为第一个参数传递给List方法。“ - 第203页

+0

为什么? – Liam

+0

@Liam我已经做了教程。你为什么downvote? – Andrew

+0

但它肩不过抛出System.NullReferenceException。 PS我没有downvote。 – ysrb