我正在嘗試測試控制器的Index
操作。該操作使用AutoMapper將域Customer
對象映射到視圖模型TestCustomerForm
。雖然這是有效的,但我擔心測試我從Index
操作收到的結果的最佳方法。使用Automapper映射ViewModel後,我應該如何測試?
控制器的索引操作是這樣的:
public ActionResult Index()
{
TestCustomerForm cust = Mapper.Map<Customer,
TestCustomerForm>(_repository.GetCustomerByLogin(CurrentUserLoginName));
return View(cust);
}
而且它TestMethod
看起來是這樣的:
[TestMethod]
public void IndexShouldReturnCustomerWithMachines()
{
// arrange
var customer = SetupCustomerForRepository(); // gets a boiler plate customer
var testController = CreateTestController();
// act
ViewResult result = testController.Index() as ViewResult;
// assert
Assert.AreEqual(customer.MachineList.Count(),
(result.ViewData.Model as TestCustomerForm).MachineList.Count());
}
在CreateTestController
方法我用Rhino.Mocks
嘲笑客戶資料庫,並設置它從SetupCustomerForRepository
退回客戶。通過這種方式,我知道當Index
操作調用_repository.GetCustomerByLogin(CurrentUserLoginName)
時,存儲庫將返回目標客戶。因此,我認爲一個相等的計數足以滿足IndexShouldReturnCustomerWithMachines
。
所有這些說我擔心我應該測試什麼。
- 看起來放肆
result.ViewData.Model as TestCustomerForm
。這真的是一個問題嗎?這與我有關,因爲在這種情況下,我並不真正在做測試驅動開發,而且我似乎在指望某個特定的實現來滿足測試。 - 是否有更合適的測試來確保正確的映射?
- 我應該從
TestCustomerForm
測試每個映射的屬性嗎? - 是否有更多的一般控制器動作測試,我應該做的?
很好的回答,這很有意義。爲了後代你會介意添加你的測試陳述嗎? – ahsteele 2010-06-21 15:40:33
這將如何與新的WebApi,我的Get方法返回一個IEnumerable而不是一個行動結果? –
shashi
2012-08-31 10:25:24
@sassyboy我傾向於使用帶有web api的獨立服務層,您可以在其中創建類似的抽象。 – 2013-07-12 19:18:57