• Senior Software Engineer • Focused on Customers and Craftsmanship • Leader of the Phoenix Software Engineering Reading Group Mike is a DZone MVB and is not an employee of DZone and has posted 20 posts at DZone. You can read more from them at their website. View Full User Profile

Consider assertThat() in place of assertEquals()

  • submit to reddit

JUnit 4.4 added a new assertion mechanism with the method assertThat(). Have a look and consider using it in place of assertEquals().

assertThat(result, is(42));
assertThat(output, containsString("foo"));
Published at DZone with permission of Mike Christianson, author and DZone MVB. (source)

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)


Jeroen Van Dijk replied on Wed, 2012/10/10 - 7:09am

Why? What's the advantage?

For what I see now is that it's more readable for normal people. But only programmers write those tests, and they understand the 'old' way without any problem...

Although I AM in favor of writing readable code, assertEquals("this is no good", thisOne, thatOne)is readable imho, even more, when we're talking about assertThat(result, is(true)) versus assertTrue(result)...

Martin Tilma replied on Wed, 2012/10/10 - 8:19am

If you read the JUnit 4.4 added a new assertion mechanism you can see some advantages

Tomasz Nurkiewicz replied on Wed, 2012/10/10 - 8:32am

Even better, use FEST assertions:




Note that your example is a bit confusing. You are checking whether "result" variable is equal to 42 and contains "foo" string - at the same time.

Jeroen Van Dijk replied on Wed, 2012/10/10 - 9:12am in response to: Martin Tilma

Tnx, I will read that :)

David Karr replied on Wed, 2012/10/10 - 11:33am

I replaced JUnit asserts with fest-assert a long time ago, and this change doesn't motivate me to return.  Fluent and readable code is a significant value.

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.