Thomas Sundberg

November 6, 2015

Different asserts are good in different situations

Filed under: Java, Teaching — Tags: , , , — Thomas Sundberg @ 11:49

This post has been migrated to

When should you use which assert? It is a question developers new to unit tests may ask themselves.

It is easy as a seasoned developer to think that this is obvious. It isn’t when you are learning.

I had a conversation today where the person I talked to used assertTrue and had a failing test. The reason why the test failed was not clear. I realized after our conversation that it might have been a better idea to use another assert. But why would that be a good idea? Let me give you an example that you can run and figure out the answer to that question yourself.

Different asserts report the result in different ways

I compare assertTrue and assertThat in the examples below. One of them will give me a better error report when something goes wrong.

My recommendation is that you run this test a few times and changes what complicatedFunction() returns to get a feeling why one of assertTrue and assertThat is better in many situations.

Run this code:

package se.thinkcode; import org.junit.Test; import static; import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; public class CompareAsserts { @Test public void assertTrueExample() { assertTrue(complicatedFunction().equals("bar")); String message = "Expected bar, got " + complicatedFunction(); assertTrue(message, complicatedFunction().equals("bar")); } @Test public void assertThatExample() { assertThat(complicatedFunction(), is("bar")); } private String complicatedFunction() { return "bar"; } }

What happened? Did you get a feeling about the differences?

My I prefer assertThat in almost every situation. My motivation is that I get better feedback. You may have other opinions. I would be interested in hearing them.


Leave a Comment »

No comments yet.

RSS feed for comments on this post. TrackBack URI

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Blog at

%d bloggers like this: