Filed under: Java, TDD, Teaching, — Tags: JUnit, assertThat, assertTrue — Thomas Sundberg — 2015-11-06
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.
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 org.hamcrest.core.Is.is; 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.