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!
 

39 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).

Unknown 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

Unknown 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

Unknown 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.

Unknown said...



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

Installment loans
Payday loans
Title loans

Anonymous 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

Anonymous 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

Maureen said...

Attention! Attention!! Attention!!!,

What is your situation? *Need 100% financing *Can't verify income *Can't verify employment *Recently self employed *Bankruptcy Collections *Credit issues *Accumulated Bills Settlement * Personal Investment Project or Company Investment Projects e.t.c. Apply for a quick and convenient loan to pay off bills and debts, start a new business or refinance your projects and expand your business in this year 2017 at the cheapest interest rate of %. For more details email
us today via email:(bdsfn.com@gmail.com)
Name :
Country :
Phone number :
Amount Needed as Loan :
Purpose of Loan :
Have you applied for loan online before (yes or no)
Email : bdsfn.com@gmail.com
Emaill: anatiliatextileltd@gmail.com

Attention! Attention!! Attention!!!,

What is your situation? *Need 100% financing *Can't verify income *Can't verify employment *Recently self employed *Bankruptcy Collections *Credit issues *Accumulated Bills Settlement * Personal Investment Project or Company Investment Projects e.t.c. Apply for a quick and convenient loan to pay off bills and debts, start a new business or refinance your projects and expand your business in this year 2017 at the cheapest interest rate of %. For more details email
us today via email:(bdsfn.com@gmail.com)
Name :
Country :
Phone number :
Amount Needed as Loan :
Purpose of Loan :
Have you applied for loan online before (yes or no)
Email : bdsfn.com@gmail.com
Emaill: anatiliatextileltd@gmail.com
Mrs.Emilia Fedorcakova

URGENT LOAN OFFER WHATSAPP +918929509036 said...

Hello Everybody,
My name is Mrs Sharon Sim. I live in Singapore and i am a happy woman today? and i told my self that any lender that rescue my family from our poor 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 S$250,000.00 to start my life all over as i am a single mother with 3 kids I met this honest and GOD fearing man loan lender that help me with a loan of S$250,000.00 SG. Dollar, he is a GOD fearing man, if you are in need of loan and you will pay back the loan please contact him tell him that is Mrs Sharon, that refer you to him. contact Dr Purva Pius,via email:(urgentloan22@gmail.com) Thank you.

Unknown said...

We Offers Financial Consulting To Client, Companies Seeking Debt / Loan Financing And Seeking For Working Capital To Start A New Business Or To Expand Existing Business. Interested Parties Should Contact Us For More Information Through Via E-mail: SuiteCapitals@gmail.com ( SuiteCapitals@post.com )

We Have Loan Programs Tailored For Any Profile And You've Come To The Right Place To Satisfy Your Business Needs. If Your Company Or You Know Of Any Company With Viable Projects / Proposals That Needs Financing, Kindly Write Us With The Loan Requirement. Please, Contact Us For More Information: SuiteCapitals@gmail.com ( SuiteCapitals@post.com )

You Will Hear From Us. Well Nice To Meet You And I look forward to our Business Acquaintance. Interested Parties Should Contact Us For More Information Through Via E-mail: SuiteCapitals@gmail.com ( SuiteCapitals@post.com )

Do You Need A Loan To Consolidate Your Debt At 1.0%? Or A Personal Loans * Business Loans etc. Interested Parties Should Contact Us For More Information Through Via E-mail: SuiteCapitals@gmail.com ( SuiteCapitals@post.com )

We Offers Financial Consulting To Client, Companies Seeking Debt / Loan Financing And Seeking For Working Capital To Start A New Business Or To Expand Existing Business. Interested Parties Should Contact Us For More Information Through Via E-mail: SuiteCapitals@gmail.com ( SuiteCapitals@post.com )

Kindly write us back with the loan information;
- Complete Name:
- Loan amount needed:
- Loan Duration:
- Purpose of loan:
- City / Country:
- Telephone:
- How Did You Hear About Us:

Do You Need A Loan To Consolidate Your Debt At 1.0%? Or A Personal Loans * Business Loans etc. Interested Parties Should Contact Us For More Information Through Via E-mail: SuiteCapitals@gmail.com ( SuiteCapitals@post.com )

We Offers Financial Consulting To Client, Companies Seeking Debt / Loan Financing And Seeking For Working Capital To Start A New Business Or To Expand Existing Business. Interested Parties Should Contact Us For More Information Through Via E-mail: SuiteCapitals@gmail.com ( SuiteCapitals@post.com )

Jamesterra said...

We are authorized Financial consulting firm that work directly with
A rated banks eg Lloyds Bank,Barclays Bank,HSBC bank etc

We provide BG, SBLC,and lots more for clients all over the world.

We are equally ready to work with Brokers and financial
consultants/consulting firms in their respective countries.

Our procedures are most reasonable and safest as we operate a 100% financial risk free process which entails that the issuing and receiving bank continues the transaction immediately after DOA is countersigned

We offer certifiable and verifiable bank instruments via Swift Transmission from a genuine provider capable of taking up time bound transactions. We are RWA ready to close leasing with any interested client in few banking days

We hope to establish a long term business relationship with you even after this first trial

Regards
WALSH SMITH, ROBERT
email : info.iqfinanceplc@gmail.com
skype: cpt_young1
Tel contact: +447031968934
Registered No: 04374045

YUSUF said...

KARNA RASA HATI YANG GEMBIRA BERKAT BANTUAN AKI SOLEH
MAKANYA SENGAJA NAMA BELIAU SAYA CANTUNKAN DI INTERNET !!!

assalamualaikum wr, wb, saya YUSUF saya Mengucapkan banyak2
Terima kasih kepada: AKI SOLEH
atas nomor togelnya yang kemarin AKI berikan "4D"
alhamdulillah ternyata itu benar2 tembus AKI
dan berkat bantuan AKI SOLEH saya bisa melunasi semua hutan2…
orang tua saya yang ada di BANK BRI dan bukan hanya itu AKI alhamdulillah,
sekarang saya sudah bisa bermodal sedikit untuk mencukupi kebutuhan keluarga saya sehari2.
Itu semua berkat bantuan AKI SOLEH sekali lagi makasih banyak ya, AKI
yang ingin merubah nasib
seperti saya...?
SILAHKAN GABUNG SAMA AKI SOLEH No; { 082-313-336-747 }

Sebelum Gabung Sama AKI Baca Duluh Kata2 Yang Dibawah Ini
Apakah anda termasuk dalam kategori di bawah ini...!!
1: Di kejar2 tagihan hutang..
2: Selaluh kalah dalam bermain togel
3: Barang berharga sudah
terjual buat judi togel..
4: Sudah kemana2 tapi tidak
menghasilkan, solusi yang tepat..!
5: Sudah banyak dukun ditempati minta angka ritual blom dapat juga,
6: Pelet pemikat hati untuk pria
7: Pesugihan tanpah tumbal
8: Dukun santet paling ampuh
satu jalan menyelesaikan masalah anda..
Dijamin anda akan berhasil
silahkan buktikan sendiri
Atau Chat/Tlpn di WhatsApp (WA)
No WA Aki : 082313336747

TERIMA KASIH YANG PUNYA
ROOM ATAS TUMPANGANYA SELAM KOMPAK SELALU

(1)"http://angkaramalantogel.blogspot.co.id/"

(2) "Pelet Khusus Untuk Pemikat Hati Pria"

(3) "Ilmu Santet Ganas"

(4) "Asli Pusat Pesugihan Putih Tanpa Resiko"

YUSUF said...

KARNA RASA HATI YANG GEMBIRA BERKAT BANTUAN AKI SOLEH
MAKANYA SENGAJA NAMA BELIAU SAYA CANTUNKAN DI INTERNET !!!

assalamualaikum wr, wb, saya YUSUF saya Mengucapkan banyak2
Terima kasih kepada: AKI SOLEH
atas nomor togelnya yang kemarin AKI berikan "4D"
alhamdulillah ternyata itu benar2 tembus AKI
dan berkat bantuan AKI SOLEH saya bisa melunasi semua hutan2…
orang tua saya yang ada di BANK BRI dan bukan hanya itu AKI alhamdulillah,
sekarang saya sudah bisa bermodal sedikit untuk mencukupi kebutuhan keluarga saya sehari2.
Itu semua berkat bantuan AKI SOLEH sekali lagi makasih banyak ya, AKI
yang ingin merubah nasib
seperti saya...?
SILAHKAN GABUNG SAMA AKI SOLEH No; { 082-313-336-747 }

Sebelum Gabung Sama AKI Baca Duluh Kata2 Yang Dibawah Ini
Apakah anda termasuk dalam kategori di bawah ini...!!
1: Di kejar2 tagihan hutang..
2: Selaluh kalah dalam bermain togel
3: Barang berharga sudah
terjual buat judi togel..
4: Sudah kemana2 tapi tidak
menghasilkan, solusi yang tepat..!
5: Sudah banyak dukun ditempati minta angka ritual blom dapat juga,
6: Pelet pemikat hati untuk pria
7: Pesugihan tanpah tumbal
8: Dukun santet paling ampuh
satu jalan menyelesaikan masalah anda..
Dijamin anda akan berhasil
silahkan buktikan sendiri
Atau Chat/Tlpn di WhatsApp (WA)
No WA Aki : 082313336747

TERIMA KASIH YANG PUNYA
ROOM ATAS TUMPANGANYA SELAM KOMPAK SELALU

(1)"http://angkaramalantogel.blogspot.co.id/"

(2) "Pelet Khusus Untuk Pemikat Hati Pria"

(3) "Ilmu Santet Ganas"

(4) "Asli Pusat Pesugihan Putih Tanpa Resiko"

basha said...

Excellent blog I visit this blog it's really awesome. The important thing is that in this blog content written clearly and understandable. The content of information is very informative.
Oracle Fusion HCM Online Training
Oracle Fusion SCM Online Training
Oracle Fusion Financials Online Training
Big Data and Hadoop Training In Hyderabad
oracle fusion financials classroom training
Workday HCM Online Training
Oracle Fusion HCM Classroom Training
Workday HCM Online Training

Chiến SEOCAM said...

Veoma sam sretan što vidim ovaj vaš zanimljiv članak. Nadam se da ćete imati više dobrih članaka


lưới chống chuột

cửa lưới dạng xếp

cửa lưới tự cuốn

cửa lưới chống muỗi

shivani said...

A bewildering web journal I visit this blog, it's unfathomably heavenly. Oddly, in this present blog's substance made purpose of actuality and reasonable. The substance of data is informative
Oracle Fusion Financials Online Training
Oracle Fusion HCM Online Training
Oracle Fusion SCM Online Training

Mika Farron said...

yang handal, Anda juga tidak boleh bermain taruhan secara asal. Gunakan tips bermain terbaik yang sesuai dengan gaya bermain. Usahakan untuk selalu fokus ketika bermain taruhan
asikqq
dewaqq
sumoqq
interqq
pionpoker
bandar ceme
betgratis
paito warna
prediksi sgp

luckys said...

whatsapp groups

luckys said...

1movies

shivani said...

A befuddling web diary I visit this blog, it's incredibly grand. Strangely, in this present blog's substance made motivation behind fact and sensible. The substance of information is instructive
Oracle Fusion Financials Online Training
Oracle Fusion HCM Online Training
Oracle Fusion SCM Online Training

luckys said...

gomovies

Raj Maan said...

movies whatsapp groups

Devender Gupta said...

fb name stylish
fb stylish name
stylish names on fb
facebook stylish name
stylish names for facebook
stylish names for fb
free netflix account
netflix accounts free
netflix premium account
netflix cookies
Netflix mod
Netflix mod apk

Devender Gupta said...

https://dtcbus.online/
https://dtcbus.online/pass
https://dtcbus.online/route
https://dtcbus.online/download

Devender Gupta said...

funny WiFi names
cool WiFi names
claver WiFi names
cool and claver WiFi names
funny WiFi names list
Good wifi names
wifi names 2020
Disney wifi names
wifi name for gamers
bollywood movies funny WiFi names

Entertaining Game Channel said...

This is Very very nice article. Everyone should read. Thanks for sharing. Don't miss WORLD'S BEST GAMES

Sandhu said...

Minecraft x-ray resource pack
Satta king 786
dhankesari
Filmyhit
Xray texture pack
xray ultimate texture packs
optifine hd mod
Naukar Vahuti Full movie download
Mission Mangal Full movie download

Sandhu said...

Filmyhit
teri meri jodi full movie download Filmyhit
section 375 full movie download Filmyhit
fauji di family full movie download
family 420 full movie download
Vipp2541
Filmyhit Download Hollywood Bollywood movies
Sanju Full Movie Download Filmyhit
Whatsapp Group Links
Whatsapp Group Links

Devender Gupta said...

Dr Driving is one of the my favourite game ever and today I am going to share Dr Driving Mod Apk
https://www.drdrivingmodapk.xyz/

Soft Online Training said...

Good Information Thanks for Sharing
Soft Online Provides best online training for Oracle Fusion and EBS R12 Courses
Oracle EBS Training in Hyderabad
Oracle Fusion SCM Training
Oracle Fusion HCM Training
Oracle Fusion Financials Training
For more info Visit us: https://www.softonlinetraining.com/

Dolores Delgado said...


Do you need any kind of loan if yes my contract Mr Anthony who help me with a loan just few week's back , i just need to share this round the world to let people know that there are still good heated people in the world today . I really lost money to scammers online all because i was desperate for a loan . Until i saw a comment about him , contacting him his not a mistake but a dreams come through for me . Now I'm a happy man with my family . Contact him if you need any loan at : challotloan@gmail.com

Chaves Truid said...

maka Anda dapat mencoba untuk menggabungkan kamar yang memiliki jumlah pemain yang sangat rendah, yang sangat mengurangi kontes. Di sisi lain, jika Anda seorang pemula dan hanya bergantung pada keberuntungan 98toto

Asoi said...

Situs Judi Slot

Unknown said...

Do You Need A Loan To Consolidate Your Debt At 1.0%? RMPCapitals@gmail.com ( RMPCapitals@usa.com ) Or A Personal Loans * Business Loans etc. Interested Parties Should Contact Us For More Information Through Via E-mail: RMPCapitals@gmail.com ( RMPCapitals@usa.com )

Please Fill the Application Form Below: -
Complete Name: - Loan amount needed: -
Loan Duration: -
Purpose of loan: -
City / Country: -
Telephone: -
How Did You Hear About Us:

Do You Need A Loan To Consolidate Your Debt At 1.0%? RMPCapitals@gmail.com ( RMPCapitals@usa.com ) Or A Personal Loans * Business Loans etc. Interested Parties Should Contact Us For More Information Through Via E-mail: RMPCapitals@gmail.com ( RMPCapitals@usa.com )