开发者

Assert on something which may not be there - nullreferenceexception

开发者 https://www.devze.com 2023-04-13 01:46 出处:网络
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?

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:

Assert on something which may not be there - nullreferenceexception

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 )
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号