Assert on something which may not be there - nullreferenceexception
Using nUnit. result is a ViewResult coming back from an MVC3 controller - it may or may not be there.
This works, but smells! Is there a better way?
string errorMessage = "";
开发者_运维知识库try {
errorMessage = result.TempData["Error"].ToString();
}
catch {}
Assert.IsNullOrEmpty(errorMessage);
UPDATE1 Getting closer... but can't get the right error message out of the test as shown below:
UPDATE2: Refactored to this:
string errorMessage = "";
if (result != null)
errorMessage = result.TempData["Error"].ToString();
Assert.IsEmpty(errorMessage);
UPDATE3: in response to @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);
}
No need to a try/catch.
You are testing for null, not that there is an empty string.
Assert.IsNull(result.TempData["Error"])
or
if (result != null && result.TempData["Error"] != null) errorMessage = result.TempData["Error"].ToString();
Assert.IsEmpty(errorMessage )
精彩评论