2009-07-22 114 views
1

在阅读Pro ASP.NET MVC Framework的前7章后 - 我非常推荐阅读,我会说。在我的阅读中,作者 - Steve Sanderson,触及了一些TDD实践。现在的问题是:
史蒂夫用于对控制器进行了单元测试本身,这本书的例子:
测试控制器或BusinessModel?

[Test] 
    public void List_Includes_All_Products_When_Category_IsNull() { 
     //Arrange: 
     IProductsRepository repository = MockProductsRepository(
      new Product { Name = "First Product", Category= "Cat11"}, 
      new Product { Name = "SecondProduct", Category = "Cat22" } 
     ); 
     ProductsController controller = new ProductsController(repository); 
     controller.PageSize = 10; 

     //Act: 
     var result = controller.List(null, 1); 

     //Assert: 
     Assert.IsNotNull(result, "Didn't render view!"); 
     var model = controller.ViewData.Model as IList<Product>; 
     Assert.AreEqual(2, model.Count, "Got wrong number of products!"); 
     Assert.AreEqual(model[0].Name, "First Product", "Not the expected first item."); 
     Assert.AreEqual(model[1].Name, "SecondProduct", "Not the expected second item.");   
    } 

我明白为什么史蒂夫正在测试这一点,显然他需要检查他的逻辑对ViewData标志他设置,这就是为什么他需要调用列表控制器操作,我的问题是,这足够吗?我的意思是,不应该先测试他的Model对象吗? Steve使用LINQ2SQL作为他的ORM工具,他几乎没有使用LINQ功能以外的任何东西,我的意思是这个例子只选择数据,并通过调用LINQ内置的方法进行更新;没有业务验证。在我的真实应用程序中,有很多应该做的业务验证,是否足够(或者更容易)让我在控制器级别开始测试,忽略了我的Model类(因为我认为它不是一个好主意)?
等待你的想法Gus!

回答

1

我想除了控制器测试之外,您还想为业务逻辑单独进行测试。

我正在安排我的控制器测试,就像史蒂夫。基本上,根据条件,我的控制器是否包含预期的查看数据?而已。没有断言数据或任何其他业务逻辑的内部细节 - 包含在单独的测试中的东西。

遵循您的示例,我会将其保留在Controller测试中,并假设您有一些防止负价的业务逻辑,您可能需要单独测试诸如“Product_discount_does_not_result_in_negative_price()”之类的东西Web上下文和控制器。让你的产品类中说你有一个规则,使得它的价格最低A $ 1即使一些所谓的折扣其实比实际的默认价格更多:(!一个可怕的例子,抱歉)

[Test] 
Product_discount_does_not_result_in_negative_price() { 
    Product p = new Product {price = 5, discount = 10}; 
    Assert.IsTrue(p.price == 1); //expecting the price Get() to return 1 in this case 
} 

我想如果您将测试保存在控制器级别,则会遇到问题,因此您需要在准备好之前创建测试并实施控制器。

+0

这就是我最终要做的。谢谢库尔特。公认! – Galilyou 2009-09-01 09:52:50