Juri Strumpflohner
Juri Strumpflohner Juri is a full stack developer and tech lead with a special passion for the web and frontend development. He creates online videos for Egghead.io, writes articles on his blog and for tech magazines, speaks at conferences and holds training workshops. Juri is also a recognized Google Developer Expert in Web Technologies

Testing Your SUT Against Exceptions

1 min read

When you test your method for exceptions (which is good practice) the usually naive approach - which btw I was following myself till today - is to wrap your method under test with an appropriate try-catch and set a boolean.
[TestMethod]
public void TestMapPositionUpdate_NullPosition_ShouldFireArgumentException()
{
//Setup
Position nullPosition = null;

//Exercise
bool exceptionCaught = false;
try
{
ObjectMapper.MapPositionUpdate(nullPosition, "", "", false, "someValue");
}
catch (ArgumentException)
{
exceptionCaught = true;
}

//Verify
Assert.IsTrue(exceptionCaught, "The exception should have happened");
}
I really don't like this approach because it involves writing a lot of code just to verify an exception has been raised and consequently it clutters up the test code and impacts on the readability.
Today I found that MS unit tests provides a nice attribute to overcome this problem, namely ExpectedException. This allows to nicely refactor the previous test method as follows:
[TestMethod]
[ExpectedException(typeof(ArgumentNullException))]
public void TestMapPositionUpdate_NullPosition_ShouldFireArgumentException()
{
//Setup
Position nullPosition = null;

//Exercise
ObjectMapper.MapPositionUpdate(nullPosition, "", "", false, "someValue");
}
Clean, isn't it. Already by looking at this test code, you immediately understand what it is about. If you happen to know other such interesting attributes, feel free to leave a comment ;)
Questions? Thoughts? Hit me up on Twitter
comments powered by Disqus