Testing in Java with JUnit 5 Good Parts

Frankly I was reluctant about the concept of TDD (Test Driven Development), but since then now i only see the benefits of designing and reaching the test coverage of > 70% .

My journey began with JUnit 4.12 (and then Testing was merely a concept that included ASSERT THAT something should return something expected.

But that was the old times — now in JUnit 5 - Assert.assertThat() is gone, and is replaced by much simpler and readable Assertions.assertEquals()

So typical JUnit5 code looks like this

Assertions.assertEquals(expected, actual-result-from-your-method-call);

and that’s it. If you are new to Testing this is enough for you, go be creative, comeback later. Trust me you might think this is just a statement but NO.

Think about this — now every method you write that returned a Fibonacci number of a result of factorial, etc. will be tested by this small one line. (Obviously you already did that with System.out.println() but now you won’t miss any mistakes since it will scream all over the console with red lines if you did).

If you are comfortable, get this there is Optional ARGUMENT in every Assertions :)

Well not so shocking — make sure you use the latest version of JUnit which is JUnit 5 (Jupiter) since the old one didn’t use awesome things that got improved in Java over the years. For Ex.

Assertions.assertEquals(expected, actual_result, "message if error occurs");

Best Practice is — Show in your words what you were expecting. Because months later if you yourself are reading it — it should make sense ;)

If you know how to write lambda’s you can mock a lazy initialization instead of simply passing a String Message by

Assertions.assertEquals(a, b, () -> “message is lazily loaded”);

This message / lambda message (message supplier) is present in every Assertions.assertXXX.

Now that this is done the question is what else if there in JUnit :

1. More Assertions

If this is clear enough, lets make it more interesting

2. Assumptions

How about saying I expect that my result will be different on mac so I assume that we are currently on mac and then run my test ?

If you think about it if you are not on Mac is there any point to run that test ! No.

3. Annotations (Only the Cool Ones)

JUnit5 believes in annotations so we have some cools ones

The last @RepeatedTest will have an output like

So, that’s it for now — Do let me know if you learned something new :)

Like what you read? Give Saurabh Kumar a round of applause.

From a quick cheer to a standing ovation, clap to show how much you enjoyed this story.