Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unit test exception messages with xUnit

I'm currently converting my MsTest unit tests to xUnit. With xUnit, is there a way to test exception messages? Is it correct to test exception messages as opposed just the exception type?

like image 449
sduplooy Avatar asked Mar 21 '11 10:03

sduplooy


People also ask

Can we use try catch in unit test C#?

In your unit test case, you can use a try-catch block.

Do xUnit tests run in parallel?

Running unit tests in parallel is a new feature in xUnit.net version 2. There are two essential motivations that drove us to not only enable parallelization, but also for it to be a feature that's enabled by default: As unit testing has become more prevalent, so too have the number of unit tests.


5 Answers

I think it is correct to test for both Exception type and message. And both are easy in xUnit:

var exception = Assert.Throws<AuthenticationException>(() => DoSomething());
Assert.Equal(message, exception.Message);
like image 142
the_joric Avatar answered Oct 03 '22 02:10

the_joric


Better to use the Record.Exception method as it matches the AAA pattern:

    [Fact]
    public void Divide_TwoNumbers_ExpectException()
    {
        var sut = new Calculator();
        var exception = Record.Exception(() => sut.Divide(10, 0));
        Assert.IsType(typeof(DivideByZeroException), exception);
    }

Hope this helps ...

like image 20
user1829319 Avatar answered Oct 03 '22 03:10

user1829319


Something like this

 var ex = Record.Exception(() => DoSomeThing());
 Assert.IsType(typeof(ArgumentNullException), ex);
 Assert.True(ex.Message.Contains("Your exception message"));
like image 39
user2982369 Avatar answered Oct 03 '22 01:10

user2982369


xUnit uses Assert.Throws to test for exception types. You could catch the exception and Assert against the message if you needed. I think in general you want to test that the expected exception is thrown, and the exact message is really not necessary.

Assert.Throws<ArgumentNullException>()

The exception might be if you have a custom exception you are unit testing and you want to make sure the message generated is what you expect. Or if there are two ways that the same exception type can be thrown but with different messages, then asserting against the message would be valuable

like image 27
NerdFury Avatar answered Oct 03 '22 03:10

NerdFury


BTW, Resharper prefers not to use typeof and suggests Assert.IsType instead, e.g.

var ex = Record.Exception(() => new FooController(null, null));
Assert.IsType<ArgumentNullException>(ex);
like image 38
Andy Creigh Avatar answered Oct 03 '22 02:10

Andy Creigh