2012-06-25 25 views
1

我有一個Action波紋管:如何檢查模型屬性的單元測試

public ActionResult SaveAndExit() 
{ 
    ViewModel1 viewModel = new ViewModel1(); 

    return View("Index", viewModel); 
} 

在單元測試我要檢查,如果視圖Reg在視圖模型爲空或不是。任何建議請

測試:

//act 
var result = controller.SaveAndExit(viewModel) as ViewResult; 

//assert 
//Assert.IsNotNull(!result.Model["Reg"].Equals(null)); 
+2

即斷言是相當混亂...您正在檢查null,然後檢查結果是否爲空。這是不是自行工作? Assert.IsNotNull(result.Model [「Reg」]) –

+0

沒錯。你正在調用'Assert.IsNotNull(boolean)' – hometoast

+0

@GazWinter這行代碼是錯誤的。模型不允許訪問它的屬性。謝謝 – user1211185

回答

7

我會傾向於寫斷言如下(使用微軟測試框架,聲稱在這裏 - 你沒有指定NUnit的):如果事情是不是

// Act 
ActionResult result = controller.SaveAndExit(viewModel); 

// Assert 
Assert.IsInstanceOfType(result, typeof(ViewResult)); 
ViewResult viewResult = (ViewResult)result; 

Assert.IsInstanceOfType(viewResult.Model, typeof(ViewModel1)); 
ViewModel1 model = (ViewModel1)viewResult.Model; 

Assert.IsNotNull(model.Reg); 
+0

嗨,在調試模型中,reg是空的,但它的拋出異常'Assert.IsNotNull失敗。' – user1211185

+0

@ user1211185這就是Assert的要點。你斷言Reg不爲null,如果是,那麼你的測試應該失敗。 – magritte

+0

**工作**用'Assert.IsNotNull(model.Reg);'替換'Assert.IsNull(model.Reg);'....很多謝謝 – user1211185

0

單元測試應該測試業務邏輯。你不需要編寫一個單元測試只是爲了檢查一些屬性爲null。

+1

除非您正在修復渲染視圖時拋出空引用異常的錯誤。沒有理由這不是一個「值得」的測試。 – hometoast

+1

@ user1211185,我建議看看[單元測試最佳實踐](http://osherove.com/videos/2009/8/25/unit-testing-best-practices.html)。無論如何,確保這個鏈接對你有用。 – Shymep