开发者

Conflicting results when unit testing MVC controller

I'm writing unit tests (using NUnit & Moq) for my MVC 2 controllers, and am following examples in the 开发者_StackOverflow社区Pro ASP.net MVC 2 Framework book by Steven Sanderson (great book, btw). However, I've run into problems, which I think are just due to my lack of understanding of NUnit.

Here's an excerpt, with the irrelevant parts removed:

[Test]
public void Cannot_Save_Invalid_Event()
{
    ...

    repository.Setup(x => x.SaveEvent(evt)).Callback(Assert.Fail);

    ...

    repository.Verify(x => x.SaveEvent(evt));
}

This test is passing for me, although from what I understand, those two statements should directly conflict with each other. The second one wasn't there originally, but I put it in to verify that it was passing for the right reasons.

From what I understand, my repository is set up to fail if "repository.SaveEvent(evt)" is called. However, later in the test, I try to verify that "repository.SaveEvent(evt)" was called. Since it passes, doesn't this mean that it was both called, and not called? Perhaps those statements don't act as I suspect they do.

Can someone explain how these two statements are not opposites, and how they can both exist and the test still pass?


Maybe your tests doesn-t fail beacuse it has a catch-everything block that also hides the assert/verify-exception that is necessary for the test to fail.

Note: the following unittest will allways pass

[Test]
public void HidingAssertionFailure()
{
    try {
        Assert.AreEqual(0,1); // this should fail
    } catch (Exception ex) {
        // this will hide the assertion failure
    }
}


The reason for this behavior was that it was running "SaveEvent()", however, since the mocked repository didn't define that action, it was throwing an exception in my controller, which my controller was catching.

So, it seems that the callback will only execute if control returns successfully.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜