Question

I quote this post from exubero's entry. I think this entry will benefit everyone who is doing a unit test:

There are a large number of different methods beginning with assert defined in Junit's Assert class. Each of these methods has slightly different arguments and semantics about what they are asserting.

The following shows some irregular uses of assertTrue:

assertTrue("Objects must be the same", expected == actual);
assertTrue("Objects must be equal", expected.equals(actual));
assertTrue("Object must be null", actual == null);
assertTrue("Object must not be null", actual != null);

Some unit testing experts pointed out that the above code could be better written as:

assertSame("Objects must be the same", expected, actual);
assertEquals("Objects must be equal", expected, actual);
assertNull("Object must be null", actual);
assertNotNull("Object must not be null", actual);

One of the advantage of using the appropriate 'assertXXX()' will increase the readability of the unit test. Can anyone point out what other benefit of using the appropriate 'assertXXX()' ?

Was it helpful?

Solution

I'm not a Java developer and I don't know what JUnit outputs when an assertion fails. Many unit testing frameworks that I've been using output better error information when use something like assertEquals.

Let me show you an example what I'm talking about:

assertTrue("Objects must be equal", "One" == "Two");
assertEquals("Objects must be equal", "One", "Two");

In first case you can have an error output like this:

Error: Expected true actual was false.

Output for the second case:

Error: Exected "One" actual was "Two".

As you can see the second case gives better more meaningful information.

OTHER TIPS

In addition to what @Vadim daid above, using the proper assert may guard against bugs created by cut-copy-paste of tests.

As an example

assertTrue("Objects must not be the same", expected != actual);

Is then copied and modified to

assertTrue("Objects must not be the same", newobject == actual);

When the code changes and this test fails and the comment fools the next developer to "fix" the code in a way that introduces a new bug.

If the cut-copy-paste-code was something like this:

assertFalse("Objects must be the same", newobject == actual);

The dis-congruity of the comment, the assertion and the test case may be more noticeable.

And yes, I've seen this happen.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top