This post has been migrated to http://www.thinkcode.se/blog/2015/11/06/different-asserts-are-good-in-different-situations
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
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
assertThat is better in many situations.
Run this code:
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.
- Thomas Sundberg – The author