2011-10-13 39 views
1

使用nUnit。結果是從MVC3控制器返回的ViewResult - 它可能會或可能不會在那裏。斷言可能不存在的東西 - nullreferenceexception

這個工程,但氣味!有沒有更好的辦法?

 string errorMessage = ""; 
     try { 
      errorMessage = result.TempData["Error"].ToString(); 
     } 
     catch {} 
     Assert.IsNullOrEmpty(errorMessage); 

UPDATE1 越來越近......但是不能得到正確的錯誤信息進行的檢測,如下圖所示: enter image description here

UPDATE2: 重構這樣:

 string errorMessage = ""; 
     if (result != null) 
      errorMessage = result.TempData["Error"].ToString(); 
     Assert.IsEmpty(errorMessage); 

UPDATE3: 迴應@Peri

public void new_trick_should_be_saved_without_error() { 
     var controller = new TricksController(); 
     var formCollection = new FormCollection() { 
                { "Name", "asdf" }, 
                { "Description", "test descr"}, 
                { "Votes", "4" } 
                }; 
     var result = controller.Create(formCollection) as ViewResult; 

     string errorMessage = ""; 
     if (result != null) 
      errorMessage = result.TempData["Error"].ToString(); 
     Assert.IsEmpty(errorMessage); 
    } 
+0

看起來有一些錯誤的測試,如果你要測試,如果結果!= NULL。 –

+0

可能..已在上面的更新3中。 –

+0

爲什麼Create會返回ViewResult或者其他呢?基於這些FormCollection中的值不應該總是返回ViewResult或者總是這樣? –

回答

1

不需要嘗試/捕獲。

您正在測試null,而不是有空字符串。

Assert.IsNull(result.TempData["Error"]) 

if (result != null && result.TempData["Error"] != null) errorMessage = result.TempData["Error"].ToString(); 
Assert.IsEmpty(errorMessage) 
+0

Cheer @Valamas - 添加了以上3種不同情況的屏幕截圖。 –

+0

結果爲空。已經更新了我的答案。不過,我建議一個靜態函數GetErrorMessage(結果結果)。你可以在那裏放置空的檢查,並且總是至少返回一個空或空字符串。使測試更簡單,更易讀。 –

+0

再次感謝@Valamas - 我會盡量簡化當前的代碼,所以拿出一張支票並放在上面的代碼中。感謝您對靜態fn的建議。 –