September 18, 2012

Brief Overview of Java Assertions

What are asserts?

An assertion is a predicate (a true–false statement) placed in a program to indicate that the developer thinks that the predicate is always true at that place. [wikipedia]

Traditional asserts

Traditional testing frameworks started with the built in keyword assert.

An example of the keyword assert:

assert <condition> value

Assert has a few drawbacks including stopping the test execution and lengthy and hard to describe assert statements.

Second generation assertions

Along comes JUnit's assert framework. Built on top of the assert keyword, JUnit provided developers the ability to be more descriptive about the testing statements.

An example of JUnit's asserts:
// asserts that the condition must be true
assertTrue("This should be true", "abc".equalsIgnoreCase("ABC"));
// asserts that the object must not be null
assertNotNull(new MyObject());
assertFalse(false == true);
// etc...

While there are some improvements on readability and usability to the basic assert keyword provided by JUnit, they share some of the same drawbacks in that many developers just use the "assertTrue()", "assertEquals()" and "assertFalse()" methods still providing a very cryptic assertion statement.

Third generation assertions

In an effort to guide developers into writing test assertions that are more readable and usable the Hamcrest library was created which switched the philosophy from many assert functions to just one basic function. The fundamental thought is that the assert is the same but the conditions will change. Hamcrest was built using the concepts of BDD (behavior driven design) where the test assertion is closer to that of a sentence.

An example of hamcrest assertions

public void showoffSomeHamcrestAssertsAndMatchers() {
    // asserts that string "abc" is "ABC" ignoring case
    assertThat("abc", is(equalToIgnoringCase("ABC")));
    assertThat(myObject.getFirst(), is("Mike!"));
    assertThat(myObject.getAddress(), is(notNullValue));

Hamcrest is a great improvement on top of the JUnit framework providing a flexible and readable testing platform. Hamcrest + JUnit is a comprehensive testing framework and when combined with Mockito (or other mocking framework) can provide a very descriptive and thorough unit testing solution. One of the drawbacks to using Hamcrest is that while descriptive, multiple assertions must be made to ensure that a test case has been covered. Many TDD purest agree that a test case should contain one and only one assertion, but how is this possible with a complex object? (purest will say refactoring, but oftentimes this is not feasible)

Fourth generation frameworks

And finally we come to the present with the latest assertion frameworks. Fest Assertion framework takes off where Hamcrest stopped providing a fluent style assertion framework giving the developer the ability to test objects with a single assertion.

An example of Fest assertions

public void getAddressOnStreet() {
    List<Address> addresses = addressDAO.liveOnStreet("main");
    assertThat(addresses).hasSize(10).contains(address1, address2);

As you can see, FEST exceptions provide a cleaner approach to assertions. FEST is very extensible and easy to use.


Assertions are a key tool in a professional developer's toolbox in which to stress test their code. This post is a part in a series with the culmination being a fluent style ExpectedException mechanism, backed by Fest, in which to add better clarity to your test cases when exceptions are being introduced. Feel free to read the lead up to this post; Allowing known failing JUnit Tests to pass test cases.

NOTE: This blog is providing an overview on assertion frameworks it should be noted that there are various other second and third generation testing frameworks that strive to provide better clarity and usability for testing including notables such as TestNG and JTest


Nikos Maravitsas said...

Hi Mike,

Great blog! Is there an email address I can contact you in private?

Unknown said...

Hey Nikos,

Thanks for reading my blog! You can reach me at mike |at clickconcepts |dot| com


Tomek said...

Hi Mike, even though I'm a FEST Fluent Assertions user I can not see the reasons why you think it is the next generation compared to Hamcrest. From my experience both FEST and Hamcrest have very similar capabilities and it is rather a matter of test to prefer one of them.

Unknown said...

Hey Tomek,

I have been using hamcrest and mockito for many years and I recently added FEST. You are right that they both have basically the same set of assertions so I base my comment in the readability of the code. I believe that fluent APIs are typically easier to read than several lines of code where the prefix of the line is the same ("assertThat("). Extensions to both are about the same though I find the FEST documentation to be better and more complete. The ecosystem of Hamcrest is still greater, but I assume that once FEST catches on at a mainstream level, we will see a larger community presence.

What are your thoughts?


Gulzar said...

I am very glad to visit such a useful article in which blogger very excellently briefed how to use asserts in programming. This is his short but very comprehensive work. Hope, you keep it up your same job.

محمد محود said...

شركة ترميمات بالرياض

Unknown said...

شركة تنظيف بالرياض - خصم 50%- ركن كلين للخدمات المنزلية
بجميع ارجائها كما تهتم لعمليات تنظيف اخرى مثل غسيل الموكيت بالرياض المنازل و غيرها فالهدف الاول ه راحة العملاء و اكتساب ثقتهم مهما تكلف الامر مع ضمان جودة الخدمات المقدمه و سرعة انجازها بكل سهوله و امان و على احدث و افضل الاساليب.
شركة تنظيف فلل بالرياض
وبالطبع يكون عمل تنظيف المساجد بالرياض أكثر صعوبة، حيث أن المساجد هي بيوت الله تعالى ومن الضروري أن تبقى مفتوحة دائماً لأداء الصلوات الخمس ، وعلي الشركة إتمام مهمة تنظيف الموكيت في أسرع وقت ويتم تجفيفه أيضا حتي يصبح جاهزاً للفرش والصلاة عليه في أوقات الصلوات الخمس دون تأخير .

afiah b said...

I would assume that we use more than the eyes to gauge a person's feelings. Mouth. Body language. Even voice. You could at least have given us a face in this test.
Java interview questions and answers

Java training in Chennai | Java training institute in Chennai | Java course in Chennai

Java training in Bangalore | Java training institute in Bangalore | Java course in Bangalore

Java interview questions and answers

Mounika said...

Needed to compose you a very little word to thank you yet again regarding the nice suggestions you’ve contributed here.
python Online training in chennai
python Online training in bangalore
python interview question and answers

shalinipriya said...

This is most informative and also this post most user friendly and super navigation to all posts... Thank you so much for giving this information to me.. 
Data Science training in Chennai | Data Science Training Institute in Chennai
Data science training in Bangalore | Data Science Training institute in Bangalore
Data science training in pune | Data Science training institute in Pune
Data science online training | online Data Science certification Training-Gangboard
Data Science Interview questions and answers

Unknown said...

Really very nice blog information for this one and more technical skills are improve,i like that kind of post.

rpa training in Chennai | rpa training in bangalore | best rpa training in bangalore | rpa course in bangalore | rpa training institute in bangalore | rpa training in bangalore | rpa online training

sweety said...

Good Post! Thank you so much for sharing this pretty post, it was so good to read and useful to improve my knowledge as updated one, keep blogging.
angularjs-Training in pune

angularjs-Training in chennai

angularjs Training in chennai

angularjs Training in chennai

angularjs-Training in tambaram

tamilsasi said...

Inspiring writings and I greatly admired what you have to say , I hope you continue to provide new ideas for us all and greetings success always for you.
Keep update more information..

Selenium training in bangalore
Selenium training in Chennai
Selenium training in Bangalore
Selenium training in Pune
Selenium Online training
Selenium interview questions and answers

sakthi said...

It is amazing and wonderful to visit your site.Thanks for sharing this information,this is useful to me
microsoft azure training in bangalore
rpa training in bangalore
best rpa training in bangalore
rpa online training

nikitha josh said...

Thank you so much for providing information on this. It was very useful.
Aviation Courses in Chennai
air hostess course in Chennai
airport courses in Chennai
Ground staff training in Chennai
Aviation Academy in Chennai
air hostess training in Chennai
airport management courses in Chennai
ground staff training in Chennai

Chris Hemsworth said...

The article is so informative. This is more helpful. Thanks for sharing

software testing training institute
Selenium training in chennai

web designing training institute said...

This is creative and more informative.
web designing classes
php training courses in chennai
magento 2 course

Naveen S said...

The article is awesome!!!!
Digital Marketing Course Training Institute in Chennai

Big Data Course Training Institute in Chennai

Data Science Course Training Institute in Chennai

Android Training Institute in Chennai

AngularJS Training Institute in Chennai

Anonymous said...

Great fantastic blog!!
Digital Marketing Course Training Institute in Chennai

SEO Course Training Institute in Chennai

Aruna Ram said...

Wow, great blog! I learned a lot and Really nice content. Thank you for sharing this unique information about this topic...!keep us updated.

Social Media Marketing Courses in Chennai
Social Media Marketing Courses
Excel Training in Chennai
Corporate Training in Chennai
Embedded System Course Chennai
Tableau Training in Chennai
Pega Training in Chennai
Oracle Training in Chennai
Social Media Marketing Courses in T Nagar
Social Media Marketing Courses in Anna Nagar

Tech News said...

nice blog

machine learning training in bangalore

data science training in bangalore

Tech Guy said...

Good content.
For the best AWS training in bangalore, Visit:
AWS training in bangalore

Tech News said...

Good Article
devops training in bangalore
hadoop training in bangalore
iot training in bangalore
machine learning training in bangalore
uipath training in bangalore

Tech News said...


Anonymous said...

For become best Big data/Hadoop devolopers visit -> Big Data and Hadoop Training in Bangalore

Anonymous said...

For IOT Training in Bangalore visit:
Best IOT Training in Bangalore

StateServices said...

Nice article. I liked very much. All the informations given by you are really helpful for my research. keep on posting your views.

PPC Marketing Services in Delhi
Content Writer Services in Delhi
Content Writing Company in Delhi
Web Development Services in Delhi
Ecommerce Website Development Company in Delhi
Website Designing Company in Delhi
Website Designing Service in Delhi
Graphic Designing Company in Delhi
Graphic Design Services in Delhi
Logo Design Services in Delhi
Logo Design Company in Delhi
White Label Digital Marketing Services in United States
White Label SMO Services in NYC

oxigen said...

Thank you so much for sharing this amazing information, please keep sharing...

CSP Apply
CSP Online Application
Online CSP Apply
CSP Registration
CSP Online Application
CSP Provider
Digital India CSP
Kiosk Banking
Micro Finance
CSP Kiosk Banking
Utility Payment

ramya said...

Great post very useful info thanks for this post ....
Aws training chennai | AWS course in chennai
Rpa training in chennai | RPA training course chennai
Data science online training

Realtime Experts said...

thank you so much for this nice information Article, Digitahanks for sharing your post with scm training in bangalore

Realtime Experts said...

This is amazing and really inspiring pm training in bangalore

Realtime Experts said...

It is amazing and wonderful to visit your site.Thanks for sharing this information,this is crm training in bangalore

Realtime Experts said...

I have read your blog its very attractive and impressive. I like it your ewm training in bangalore

Realtime Experts said...

Great post!I am actually getting ready to across this information,i am very happy to this commands.Also great blog here with all of the valuable information you have.Well done,its a great knowledgez.

Softgen Infotech said...

I am happy for sharing on this blog its awesome blog I really impressed. thanks for sharing.

Learn Best SAP S4 HANA Simple Finance Training in Bangalore from Experts. Softgen Infotech offers the Best S4 HANA Simple Finance Training in Bangalore.100% Placement Assistance, Live Classroom Sessions, Only Technical Profiles, 24x7 Lab Infrastructure Support.

Durai Moorthy said...

Really it was an awesome article… very interesting to read…Thanks for sharing.........
aws Training in Bangalore
python Training in Bangalore
hadoop Training in Bangalore
angular js Training in Bangalore
bigdata analytics Training in Bangalore
python Training in Bangalore
aws Training in Bangalore

bavisthra said...

Study Artificial Intelligence Course in Bangalore with ExcelR where you get a great experience and better knowledge.
Artificial Intelligence Course

bavisthra said...

Study Data Scientist Course in Bangalore with ExcelR where you get a great experience and better knowledge.
Data Scientist Course

Data Science Course said...

Really awesome blog!!!
Data Science Course
Data Science Course in Marathahalli

sasitamil said...

I simply wanted to write down a quick word to say thanks to you for those wonderful tips and hints you are showing on this site.

Selenium Training in Electronic City

subha said...

Updating with the latest technology and implementing it is the only way to survive in our niche. Thanks for making me understand through this article. You have done a great job by sharing this content in here. Keep writing article like this. share more
Ai & Artificial Intelligence Course in Chennai
PHP Training in Chennai
Ethical Hacking Course in Chennai Blue Prism Training in Chennai
UiPath Training in Chennai

BestTrainingMumbai said...

It is really great to know you being a responsible writer did take care about the information you have provided in this article. This is elegantly prepared and well-written in my opinion.
SAP training in Mumbai
Best SAP training in Mumbai
SAP training institute Mumbai

My Oxigen said...

The Banking services like, Account opening, cash deposit acceptance and cash withdrawal etc.

Apply CSP

CSP Registration

CSP Provider

Bank CSP

CSP Kisok

CSP Apply

CSP Online Application

Apply for CSP

Top CSP Provider in India

Apply Online For Bank CSP

Top CSP Provider Company in India

CSP Provider Company in India

Apply Online CSP

surya said...

Great post! I am actually getting ready to across this information, It’s very useful for this blog.Also great with all of the valuable information you have Keep up the good work you are doing well.
Angular JS Training in Chennai | Certification | Online Training Course | Angular JS Training in Bangalore | Certification | Online Training Course | Angular JS Training in Hyderabad | Certification | Online Training Course | Angular JS Training in Coimbatore | Certification | Online Training Course | Angular JS Training | Certification | Angular JS Online Training Course

radhika said...

Thanks for the post, I am techno savvy. I believe you hit the nail right on the head. I am highly impressed with your blog. It is very nicely explained.

AWS training in Chennai

AWS Online Training in Chennai

AWS training in Bangalore

AWS training in Hyderabad

AWS training in Coimbatore

AWS training

Morgan said...

Job opportunities created by Big data does not only pay handsome salaries when compared to other IT jobs, but are spread across leading industries of the world. data science course in hyderabad

Golden Triangle India Tour said...

Really nice and interesting post. I was looking for this kind of information and enjoyed reading this one. Thanks for posting this out! Amazing post and a great read! Golden Triangle India Tour

Suryaprakash said...

Thanks for sharing amazing blog. I am really happy to read your blog. Thanks for sharing your blog.
Android Training in Tambaram
Android Training in Anna Nagar
Android Training in Velachery
Android Training in T Nagar
Android Training in Porur
Android Training in OMR

maurya said...

Great blog, this gives more useful concepts and i got good information from this post.
list to string python
what is data structure in python
polymorphism real time example
numpy example in python
python interview questions and answers pdf
types of data structure in python

suresh said...

Great Article… I love to read your articles because your writing style is too good, its is very very helpful for all of us.
DevOps Training in Chennai

DevOps Course in Chennai

siva said...

Thanks for sharing your innovative blog, it's more interesting.
android app development future scope
what is webdriver in selenium
php programming languages
scope of ethical hacking
aws devops interview questions and answers
rpa interview questions for experienced

vé máy bay từ singapore về việt nam said...

Mua vé tại Aivivu, tham khảo

Lịch bay từ Hàn Quốc về Việt Nam tháng 7

vé máy bay từ thanh hóa về sài gòn

lịch bay chu lai hà nội

vé máy bay hải phòng đi nha trang

vé máy bay đi quy nhơn

Nichole Williams said...

Great information. Couldn’t be written much better!
Keep it up!
Buy Logo

Maneesha said...

All of these posts were incredibly perfect. It would be great if you’ll post more updates.
data scientist training and placement in hyderabad

data science said...

I was basically inspecting through the web filtering for certain data and ran over your blog. I am flabbergasted by the data that you have on this blog. It shows how well you welcome this subject. Bookmarked this page, will return for extra. data science course in jaipur

Сократитель said...

download tiktok video with no watermark video for instagram or youtube shorts

Mallela said...

Thanks for posting the best information and the science course in Lucknow

Arnold DK said...

Thanks for the post, I am techno savvy. I believe you hit the nail right on the head. I am highly impressed with your blog. It is very nicely explained. whatsapp mod

e visa Kenya online said...

This is really an inspiring and helpful article. I am fully satisfied with your effort .There is no need to meet Kenya embassy specially for to get a valid e visa Kenya online. The Government of Kenya grants the e visa online provide

Unknown said...

Pretty good post. I just stumbled upon your blog and wanted to say that I have really enjoyed reading your blog posts. Any way I’ll be subscribing to your feed and I hope you post again soon. data science course in kanpur

Maneesha said...

Your content is nothing short of brilliant in many ways. I think this is engaging and eye-opening material. Thank you so much for caring about your content and your readers.
data analytics course in hyderabad

Ali jan said...

The squeeze page also known as the landing page or the opt-in page is the first webpage a prospect will come across in the sales process. The prospect has not yet entered the sales funnel at this stage but it is there on that page. The word squeeze is meant to convey the 'squeezing out' or extraction of the email address and perhaps spending of the prospect as he goes through the sales funnel. Click here

360DigiTMG said...

Wonderful blog post. This is absolute magic from you! I have never seen a more wonderful post than this one. You've really made my day today with this. I hope you keep this up!
data analytics course in hyderabad

dipanshu sharma said...

Nice blog post so thanks a lot for sharing this great blog post.. keep more post for sharing.. have a nice day.
Apply for Super Visa Canada

Azerbaijan evisa requirements said...

Your blog post is a treasure trove of ideas, each one more valuable than the last. It's like embarking on a journey through the wilderness of thought, where every discovery is a triumph. Your words are like beacons of light, guiding us through the darkness of ignorance. Thank you for sharing your wisdom with us.

How many days to get a Mexico visa? said...

What a refreshing take on an often overlooked subject! Your ability to simplify complex ideas is impressive. The blend of personal anecdotes and broader themes adds depth to your writing, making it relatable and insightful. I found your style engaging, and it held my interest from start to finish. I’m excited to read more of your posts and engage in the thoughtful conversations they inspire. Keep up the excellent work.