2010-11-29 43 views
7

我完全是Moq的新手,迄今爲止只是遵循Pro asp.net框架中概述的示例。在這本書中,一些糟糕的東西被放置在控制器中,比如通過id獲取客戶 - 可能是爲了簡潔起見。我決定把這種類型的功能放在版本庫中,並在控制器中調用它,就像「customerRepository.GetCustomerByID(id);」測試類似這樣的最好方法是什麼?我創建了以下單元測試,出於某種原因返回null Customer。使用Moq的單元測試資源庫

List<Customer> customer = new List<Customer>(); 

customer.Add(new Customer { CustomerId = 1, FirstName = "test", LastName = "wods", Sex = true }); 
mockRepos = new Moq.Mock<ICustomerRepository>(); 
mockRepos.Setup(x => x.Customers).Returns(customer.AsQueryable()); 

CustomersController controller = new CustomersController(mockRepos.Object); 

//Act 
ViewResult results = controller.Edit(1); 

var custRendered = (Customer)results.ViewData.Model; 
Assert.AreEqual(2, custRendered.CustomerId); 
Assert.AreEqual("test", custRendered.FirstName); 

而且控制器

public ViewResult Edit(int id) 
{ 
    Customer customer = customerRepository.GetCustomerByID(id);   

    return View(customer); //this just returns null?? 
} 

我想我是非常愚蠢的,但任何幫助,將超級讚賞。

回答

9

您需要設置您的模擬以期望致電GetCustomerById而不是Customers屬性。類似這樣的:

mockRepos.Setup(x => x.GetCustomerById(1)).Returns(customer[0]); 
+0

完美的感謝。 – hoakey 2010-11-29 16:04:45