Sunday, May 20, 2012

Hamcrest Matchers in JUnit tests

Normal assertions in JUnit would look like this:

Assert.assertEquals(expectedValue, actualValue); for example Assert.assertEquals(3, bean.getValue());

With hamcrest matchers, we can make the tests much more expressive and with recent versions of JUnit, core hamcrest matchers are bundled with JUnit and so there is no need to download and add hamcrest to our classpath explicitly.

JUnit has this new static method in org.junit.Assert called assertThat which has signature like this:

assertThat(actual, Matcher);

Using this, we can make the tests very expressive. First add some of the static imports:

import static org.hamcrest.core.Is.is;
import static org.hamcrest.core.IsNot.not;
import static org.hamcrest.core.IsEqual.equalTo;
import static org.hamcrest.core.IsNull.nullValue;
import static org.junit.Assert.assertThat;

Then, assertions can look like this:

      assertThat(bean.getValue(), is(equalTo(3)));
      assertThat(bean.toString(), is("XYZ"));
      assertThat(bean.getNewValue(), is(nullValue());
      assertThat(bean.getType(), is(not(nullValue()));

This shows how readable these tests are when compared to the regular assertions. Also, we can see that matchers can be nested. In the above block, is and not, is and equalTo, is and nullValue() are chained to make it more readable.

There are more matchers available in org.hamcrest.core package inside junit jar. In Eclipse, you can open up the junit jar under referenced libraries and navigate to this particular folder in package explorer to see other available matchers.

Only drawback that I found is, I cannot use assertThat for comparing double values with tolerance. Other than that, I tend to assertThat for most of my assertions. It certainly makes my tests much more readable and expressive!
 

12 comments:

Shubhashish Bhowmik said...

Nice Post. And thanks for information.

John Arthorne said...

I guess it's a matter of perspective, but I find assertEquals(3, bean.getValue()) is much more readable than the hamcrest version. The assertEquals function clearly takes two values and compares them. On the other hand when I see isEqualTo(3) I am very confused. How can a function with a single argument be comparing anything? Similarly is(not(nullValue())) is just a very convoluted way of expressing something that java has a built in operator for (x!=null).

teja ul said...

Very nice article.. In order to fulfill the ever changing requirements of our prestigious clients, we are offering a comprehensive range of Precision Machined Components you can refer Precision Machined Components

craige boyle said...

If you plan on a long term career as a project manager, then yes, even with your level of experience, I would suggest getting your PMP. You can prepare yourself for the exam in one of the PMP trainingproviders like http://www.pmstudy.com/. You can do minimal prep-work to get 40 PMI® Contact Hours and apply to PMI for PMP Exam before the class begins.

Solartis said...

Thanks for sharing such a wonderful article.IASA conference

Australian Risk Services said...

Safety and risk management is a vital part of any Australian business. However doing it right and in line with the new Australian WHS legislation is a complex task where many variables need to be considered.

Unknown said...

safety auditing does more than just ensure compliance with the various acts and regulations governing occupational health and safety (OHS); it ensures that employees are kept healthy, injury-free and productive. For more information on our Safety Auditing Program or any of our other services.

ERP said...

Hi,

your article so informative and i have cleared all of my doubts.
your way of explanation is awesome thank you for sharing useful information.
the above mentioned questions some may ask in interview time thank you

regards,
Oracle Fusion Cloud HCM Training

Plant Risk Assessment | Plant Safety Assessment said...

I love the blog cotent it is very helfull for us. Plant Safety Assessment professional from Australian Risk Services can be of particular assistance at this stage. Being now familiar with your workplace, they can provide details on the best controls and practices for your situation.

Philips Huges said...



Wonderful blog.. Thanks for sharing informative Post. Its very useful to me.

Installment loans
Payday loans
Title loans

Loan Offer said...


Are you looking for a business loan, personal loans, mortgages, car
loans, student loans, debt consolidation loans, unsecured loans, risk
capital, etc. ... You are in the right place
Your loan solutions! I am a private lender who lends
Individuals and businesses at a low interest rate and affordable
Interest rate of 3%. Contact us by email: powerfinance7@gmail.com

LOAN APPLICATION FORM
**********************
Your full name:
Country/State:
Loan Amount:
Duration
Phone:
Monthly income:
Occupation:

Awaiting your swift response.
May Allah bless you.
IBRAHIM MUSA
power Financial Service Pvt.
Contact Us At :powerfinance7@gmail.com
WhatsApp Number +919717357946

RODNEY BRITTANY NICOLE said...

How I Got My Loan From A Genuine And Reliable Loan Company

My name is Mrs RODNEY BRITTANY NICOLE. I live in United State Of America working here I am from Philippines and i am a happy woman today? and i told my self that any lender that rescue my Company and my Family situation, i will refer any person that is looking for loan to him, he gave me happiness to me and my family, i was in need of a loan of $300,000,00 and was scammed by those fraudulent lenders and a friend introduce me to MR IBRAHIM MUSA,and he lend me the loan without any stress,you can contact him at (powerfinance7@gmail.com)

LOAN APPLICATION FORM
**********************
Your full name:
Country/State:
Loan Amount:
Duration
Phone:
Monthly income:
Occupation:

Awaiting your swift response.
May Allah bless you.
IBRAHIM MUSA
power Financial Service Pvt.
Contact Him At :powerfinance7@gmail.com
WhatsApp Number +919717357946