Quantcast
Channel: darkroastjava – Darkroastjava's Public Notebook
Viewing all articles
Browse latest Browse all 13

Unit Tests: An AAA-conform way to expect exceptions

$
0
0

I like the way how NUnit supports expected exceptions in unit tests – as opposed to some other frameworks, where you have to misuse a try-catch block

try
{
    DoSomething();
    Assert.Fail("exception expected");
}
catch (ExpectedException ex)
{
    // this is the good case, do nothing
}

in NUnit you can

Assert.Throws<ExpectedException>(() => DoSomething());

Or, if you want, you can make more assertions on the exception thrown:

Assert.Throws<ExpectedException>(
    () => DoSomething(),
    ex => ex.Message == "Failed to do this");

However, this unfortunately (still) breaks the AAA structure of a unit test. With only a tiny helper you can get an AAA-structured unit test that expects an exception:

// Arrange
var x = "foo";

// Act
var actualException = Catch<ExpectedException>(() => DoSomething(x));

// Assert
Assert.That(actualException, Is.Not.Null);
Assert.That(actualException.Message, Is.EqualTo("Failed to do this"));

And this is the helper:

public TException Catch<TException>(Action action)
    where TException : Exception
{
    try
    {
        action();
        return null;
    }
    catch (TException ex)
    {
        return ex;
    }
}

I think this is a big plus. What do you think? Does this approach have any drawbacks or caveats?



Viewing all articles
Browse latest Browse all 13

Trending Articles