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);
//
assertNull(null);
// 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

@Test
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

@Test
public void getAddressOnStreet() {
    List<Address> addresses = addressDAO.liveOnStreet("main");
    assertThat(addresses).hasSize(10).contains(address1, address2);
    assertThat(stringObj).hasSize(7).isEqualToIgnoringCase("abcdefg");
}

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

Conclusion

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

46 comments:

Nikos Maravitsas said...

Hi Mike,

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

Mike! said...

Hey Nikos,

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

Mike!

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.

Mike! 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?

Mike!

gulzar ahmed 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...

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

Naviya Nair 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. Your article adds best knowledge to our Java Online Training from India. or learn thru Java Online Training from India Students.

عبدالله السيد said...

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

mohamed ali said...

شركة تنظيف بخميس مشيط
شركة تنظيف منازل بخميس مشيط
شركة تنظيف كنب بخميس مشيط
شركة تنظيف خزانات بخميس مشيط
شركة عزل اسطح بخميس مشيط
شركة عزل خزانات بخميس مشيط

mohamed ali said...

شركة نقل اثاث بحائل
شركة مكافحة حشرات بحائل
شركة تنظيف خزانات بحائل
شركة تنظيف منازل بحائل
شركة تنظيف فلل بحائل

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

Seif Elsbety said...


شركة تنظيف منازل بأبها
شركة تنظيف بأبها
شركة تنظيف بالاحساء
شركه تنظيف منازل بالاحساء
شركة تنظيف بالجبيل
شركة تنظيف منازل بالجبيل

john jersy 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

ais a said...

Great post! I am actually getting ready to across this information, It’s very helpful for this blog.Also great with all of the valuable information you have Keep up the good work you are doing well.
Best Devops training in sholinganallur
Devops training in velachery
Devops training in annanagar
Devops training in tambaram

Chitra devi 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

Nadeem Malik said...

hello sir,
thanks for giving that type of information.
digital marketing company in delhi
HP DesignJet T120 In Delhi

شركة صيانة تنظيف said...

شركة دهانات بأبها

رجب البرنس said...


بسم الله الرحمن الرحيم تقدم لكم شركة الكمال جميع خدمات رش المبيد يجميع انحاء المملكة بافضل انواع

المبيدات للقضاء على جميع الحشرات الطائرة والزاحفه كالصراصير والفائران والنمل الابيض والبق

والذباب والناموس
شركة رش مبيدات بالطائف
شركة رش مبيدات بجازان
شركة رش مبيدات بحائل
والسلامه عليكم ورحمة الله وبركاته

Akash Thakur said...

Thanks for giving great kind of information. So useful and practical for me. Thanks for your excellent blog, nice work keep it up thanks for sharing the knowledge.
dining room interior designer in noida

Vikash Kumar said...

nice work keep it up thanks for sharing the knowledge.Thanks for sharing this type of information, it is so useful.
Epoxy Grout manufacturer

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

Mohamed Abdellatif said...

طرق مكافحة النمل الابيض

ajish 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.
Selenium Training in Electronic City

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

Rajesh said...

thanks for sharing this information
Amazon web services training in bangalore
best AWS Training institute in Bangalore
best training institute for data science in bangalore
best tableau training institutes in bangalore
best python training institute in bangalore
python training in jayanagar bangalore
Artificial Intelligence training in Bangalore

Pardeep Mengi said...

Usually I never comment on blogs but your article is so convincing that I never stop myself to say something about it. You’re doing a great job Man,Keep it up.
Study Abroad in New Zealand

gokul said...

Thank you for this informative blog
Top 5 Data science training in chennai
Data science training in chennai
Data science training in velachery
Data science training in OMR
Best Data science training in chennai
Data science training course content
Data science syllabus
Data science courses in chennai
Data science training institute in chennai
Data science online course
Data science with python training
Data science with R training

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 updates 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 updates 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 updates said...

visit here=> BEST DEVOPS TRAINING IN BANGALORE

Updated Tech News said...

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

Updated Tech News 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

Lovable vicky said...

Nice information, want to know about Selenium Training In Chennai
Selenium Training In Chennai
Data Science Training In Chennai
Protractor Training in Chennai
jmeter training in chennai
Rpa Training Chennai
Rpa Course Chennai
Selenium Training institute In Chennai
Python Training In Chennai

Lovable vicky said...


Rpa Training in Chennai
Rpa Course in Chennai
Blue prism training in Chennai

Data Science Training In Chennai
Data Science Course In Chennai
Data Science Course In Chennai

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