Tuesday, December 21, 2010

Assert.DoesNotThrow... why does it exist?

Take a look at this test:

[Test]
public void TestSomething()
{
   Assert.DoesNotThrow(MethodUnderTest);
}

It seems to me that it is functionally equivalent to this test:

[Test]
public void TestSomething()
{
    MethodUnderTest();
}

In other words, Assert.DoesNotThrow is the same as writing a test with no assertion. Is it really enough that the code runs without throwing an exception? Presumably the method under test is doing something, so shouldn't you verify those results with a stronger assertion?

3 comments:

  1. I find it best (for readability) to always have an assert in my test cases.

    While the code is operationally equivalent (or at least I hope it is!) the second example requires a little more of an 'aha' while reading through the test code.

    I'm not sure that it's true that you necessarily _always_ need a stronger assertion. ex: you are deserializing some information and it could be out of date, or it could not, and you don't necessarily want to enforce a contract on MethodUnderTest -- maybe it comes through and maybe it doesn't. But it's vital that it not error out when reading!

    ReplyDelete
  2. You might want this if you are validating something and the validation passes by not throwing an exception...

    ReplyDelete
  3. For example you are calling a series of void validation methods that only raise exceptions if the validation has failed.

    ReplyDelete