Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unit testing with assertTrue vs others

I work in a TDD environment and I use assertTrue a lot whereas there are many other methods, such as assert equals etc. I have a class that I have more than 40 test cases and they are all assertTrue. is this acceptable?

I wanted to ask as a style, is this proper?

any suggestions?

if u think this question is inappropriate let me know i ll delete it.

EDIT:

    assertTrue(targetSpecifiers.size() == 2);
    assertTrue(targetSpecifiers.get(0).getPlacementId().compareTo(new BigInteger("1")) ==0);
    assertTrue(targetSpecifiers.get(1).getPlacementId().compareTo(new BigInteger("2")) ==0);
like image 414
DarthVader Avatar asked Dec 04 '22 01:12

DarthVader


2 Answers

The main benefits of using other assertions is that they better communicate intent and are likely to give a more meaningful default message in the event of failure.

e.g.

if you write assertEquals(2, x) if x is actually 1 then the failure message will be:

java.lang.AssertionError: expected:<2> but was:<1>

which is more helpful than if you write assertTrue(x == 2) where all you would see is the AssertionError and the stack trace.

This is even more important when you are using TDD because you when you write a failing test first you want to be confident that the test is failing for the reason you are expecting it to and that there is not some accidental behaviour going on.

like image 176
mikej Avatar answered Dec 05 '22 14:12

mikej


Where appropriate you should use the correct assertXXX methods as they improve the reporting of failures. For e.g. if you are testing for the equality of let us say 2 string "abc" (expected) and "abxy" (actual), then the use of assertEquals

assertEquals("abc", "abxy") 

will provide a better output that is easier to reason about than using the assertTrue like below

assertTrue("abc".equals("abxy"))

NOTE: Also pay attention to where you are specifying the actual and expected arguments. I see lot of developers not following the convention (junit's convention) that the expected should be the first param to the assertXXX methods. Improper usage also leads to lot of confusion

like image 29
Aravind Yarram Avatar answered Dec 05 '22 14:12

Aravind Yarram