开发者

NUnit's TestCustomException doesn't care about the exception type

If I want to test that a method throws an exception of a particular type, NUnit's ExpectedException attribute doesn't care about the actual type; if I throw a generic Exception before the method call, the test passes:

    [Test, ExpectedException(typeof(TestCustomException))]
    public void FirstOnEmptyEnumerable()
    {
        throw new Exception(); // with this, the test should fail, but it doesn't
        this.emptyEnumerable.First(new TestCus开发者_运维百科tomException());
    }

If I want to check that the test throws the exact exception type, I have to do something manual like this:

    [Test]
    public void FirstOnEmptyEnumerable()
    {
        try
        {
            throw new Exception();  // now the test fails correctly.
            this.emptyEnumerable.First(new TestCustomException());
        }
        catch (TestCustomException)
        {
            return;
        }

        Assert.Fail("Exception not thrown.");
    }

Am I missing something?


I've never used ExpectedException, so I don't have any experience to share on this. An option is to Assert that it Throws directly inside the test. Something like this:

[Test]
public void FirstOnEmptyEnumerable()
{
    Assert.Throws<TestCustomException>(() => this.emptyEnumerable.First(new TestCustomException()));
}

I find this approach more readable as you test for the exception exactly where you expect it to happen instead of saying "somewhere inside this function I except an exception to be thrown".


I always test for the string representation of the exception e.g.:

[Test, ExpectedException("Your.Namespace.TestCustomException")]
public void FirstOnEmptyEnumerable()
{
    throw new Exception(); // with this, the test should fail, but it doesn't
    this.emptyEnumerable.First(new TestCustomException());
}

Which seems to work fine for me.


If you want to use the ExpectedException(string) signature, the best practice would be to use typeof(Exception).Name and typeof(Exception).Namespace

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜