Dave Mateer
Dave Mateer

Reputation: 6636

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: enter image description here

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);
    }

Upvotes: 1

Views: 206

Answers (1)

Valamas
Valamas

Reputation: 24759

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 )

Upvotes: 1

Related Questions