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?
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);
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 ...
Something like this
var ex = Record.Exception(() => DoSomeThing());
Assert.IsType(typeof(ArgumentNullException), ex);
Assert.True(ex.Message.Contains("Your exception message"));