AssertJ vs JUnit

Use AssertJ for fluent and more readable assertions.

Image for post
Image for post
Photo by timJ on Unsplash

What’s the difference between JUnit and AssertJ

Hi, there!

Why should I use AssertJ?

  • easy to learn: Ready to dive in AssertJ? You can find all about AssertJ here.

Took me less than half an hour to get AssertJ.

  • easy to use: you just need to add a dependency and static import in your test class to start using AssertJ.
  • fluent: AssertJ helps you to diversify your assertions.
  • more readable code
  • auto-completion: AssertJ provides auto-completion in IDEs. So you don't need to remember all method names.
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<version>3.16.1</version>
<scope>test</scope>
</dependency>
testImplementation 'org.assertj:assertj-core:3.13.2'
import static org.assertj.core.api.Assertions.*;

AssertJ in Action

Now let’s have a look at some code examples comparing JUnit and AssertJ assertions. Starting with assertEquals assertion. Here is how we usually do this in JUnit.

Image for post
Image for post
.as(String description)

Testing Collections

Here I will show just one example of using AssertJ when working with Collections. Here we are testing the TolkienCharacter class.

Testing Exceptions

In JUnit the Expected Exception rule allows us to expect an exception in the test case. Also, JUnit 4 lets you expect an exception through the @Test annotation’s expected attribute.

@Test(expected = IOException.class)

Conclusion

AssertJ is a library for writing better assertions. Using AssertJ you can write cleaner and more readable code. Plus it is super easy to learn and use. AssertJ works with any Java version over Java 6, it also supports assertions using the newer features in Java such as lambdas. Find more about methods in AssertJ here. Happy testing!

Written by

QA and free artist

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store