{"id":1338,"date":"2014-09-12T06:09:48","date_gmt":"2014-09-12T10:09:48","guid":{"rendered":"http:\/\/qxf2.com\/blog\/?p=1338"},"modified":"2015-04-12T08:41:09","modified_gmt":"2015-04-12T12:41:09","slug":"juint-asserts-and-matchers","status":"publish","type":"post","link":"https:\/\/qxf2.com\/blog\/juint-asserts-and-matchers\/","title":{"rendered":"JUint Asserts and Matchers"},"content":{"rendered":"<p><strong>Problem:<\/strong> JUnit tutorials are often written by testers with a reasonable amount of unit checking expertise<\/p>\n<h3>Why this post?<\/h3>\n<p>There are plenty of JUnit tutorials available online. They are often written by testers with a reasonable amount of unit checking experience. The problem is that experts and beginners see things differently. I began noticing that beginners often read these JUnit tutorials written by experts and come away feeling like there is a unsurmountable mountain of knowledge they need to learn before applying the concepts. So <a href=\"http:\/\/www.qxf2.com\">we<\/a> decided to try something different &#8211; writing tutorials for beginners by beginners. Rupesh Mishra, a Qxf2 Services employee, volunteered to write this post. This is PART II in a series of posts that Rupesh is writing on JUnit. The rest of the post is written by Rupesh.<\/p>\n<h3>JUnit asserts and matchers<\/h3>\n<p>There are several JUnit assertion method and they all are static methods. All these methods are stored in Assert Class which is one of the important class of JUnit framework. We can easily import this class by<\/p>\n<pre lang=\"java\">import static org.junit.Assert.*;\r\n<\/pre>\n<p>Using this Assert Class we can write set of useful assertion methods. Here is a list of all important methods of Assert Class.<\/p>\n<table style=\"background-color: #f0f0f0;\">\n<tbody>\n<tr>\n<th>Methods &amp; Description<\/th>\n<\/tr>\n<tr>\n<td><b>assertEquals(boolean expected, boolean actual);<\/b><br \/>\nCheck that two primitives\/Objects are equal<\/td>\n<\/tr>\n<tr>\n<td><b>assertTrue(boolean expected, boolean actual);<\/b><br \/>\nCheck that a condition is true<br \/>\n<b>assertFalse(boolean condition)<\/b><br \/>\nCheck that a condition is false<\/td>\n<\/tr>\n<tr>\n<td><b>assertNotNull(Object object);<\/b><br \/>\nCheck that an object isn&#8217;t null.<b>assertNull(Object object)<\/b><br \/>\nCheck that an object is null<\/td>\n<\/tr>\n<tr>\n<td><b>assertSame(boolean condition);<\/b><br \/>\nThe assertSame() methods tests if two object references point to the same object<b>assertNotSame(boolean condition)<\/b><br \/>\nThe assertNotSame() methods tests if two object references not point to the same object.<\/td>\n<\/tr>\n<tr>\n<td><b>assertArrayEquals(expectedArray, resultArray);<\/b><br \/>\nThe assertArrayEquals() method will test whether two arrays are equal to each other.<\/td>\n<\/tr>\n<tr>\n<td><b>assertThat(actual, matcher);<\/b><br \/>\nThe assertThat() method will test whether actual satisfies the condition specified by matcher.<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<p>In this post I will discuss more about the assertThat() method using Hamcrest matcher library and how to write custom matchers. Before that lets take a quick look at the other assert methods.<\/p>\n<ul>\n<li><strong>assertEquals()<\/strong><\/li>\n<\/ul>\n<p>The assertEquals() method checks that two values are equal.Compared values may be of any Java type: Boolean,float,double,short,byte,char,int,long or object.<\/p>\n<pre lang=\"java\">import static org.junit.Assert.*;\r\nimport org.junit.Test;\r\n\r\npublic class Practice_codeTest {\r\n\r\n\t@Test\r\n\tpublic void testEquals() {\r\n\t\tPractice_code InputString = new Practice_code();\r\n                \/\/Concatenating two words and storing in string variable \"result\".\r\n\t\tString result = InputString.concatenate(\"Practice\",\"Code\");\r\n                \/\/assertEquals(\"expected output\",\"actual output\" );\r\n\t\tassertEquals(\"PracticeCode\", result);\r\n\t  }\r\n}\r\n<\/pre>\n<ul>\n<li><strong>assertTrue() and assertFalse()<\/strong><\/li>\n<\/ul>\n<p>assertTrue() and assertFalse() methods are use to check that a condition is True or False.<\/p>\n<pre lang=\"java\">import static org.junit.Assert.*;\r\nimport org.junit.Test;\r\n\r\npublic class Practice_codeTest {\r\n\t\/\/Method for return True if input number will even.\r\n\tpublic boolean isEvenNumber(int number){\r\n        \r\n        boolean result = false;\r\n        if(number%2 == 0){\r\n            result = true;\r\n        }\r\n        return result;\r\n    }\r\n\r\n\t@Test\r\n\tpublic void testEvenNumbers() {\r\n\t\tPractice_codeTest newnumber = new Practice_codeTest();\r\n\t\tassertTrue(newnumber.isEvenNumber(4));\r\n\t\tassertFalse(newnumber.isEvenNumber(3));\r\n\t  }\r\n}\r\n<\/pre>\n<ul>\n<li><strong>assertNull() and assertNotNull()<\/strong><\/li>\n<\/ul>\n<p>The assertNull() and assertNotNull() methods will test whether the object value is null or not.<\/p>\n<pre lang=\"java\">import static org.junit.Assert.*;\r\nimport org.junit.Test;\r\n\r\npublic class Practice_codeTest {\r\n\t\r\n\tObject firstnumber = null;\/\/Declaring object firstnumber as a Null.\r\n\tObject secondnumber = 123;\/\/Declaring object secondnumber with value 123 that means NotNULL.\r\n\t@Test\r\n\tpublic void testNullvalues() {\r\n\t\tassertNull(firstnumber);\r\n\t\tassertNotNull(secondnumber);\r\n\t\t\r\n\t  }\r\n}\r\n<\/pre>\n<ul>\n<li><strong>assertSame() and assertNotSame()<\/strong><\/li>\n<\/ul>\n<p>The assertSame() and assertNotSame() will check whether two objects points to the same object or not,If they will points to same object then only assertSame() method will pass otherwise only assertNotSame() method will pass.<\/p>\n<pre lang=\"java\">import static org.junit.Assert.*;\r\nimport org.junit.Test;\r\n\r\npublic class Practice_codeTest {\r\n\t\r\n\tString firstnumber = new String(\"abc\");\/\/Declaring string firstnumber as a value \"abc\".\r\n\tString secondnumber = firstnumber;\/\/Declaring string secondnumber and pointing to string firstnumber.\r\n\tString thirdnumber = new String(\"abc\");\/\/Declaring string thirdnumber as a new string with value \"abc\".\r\n\t@Test\r\n\tpublic void testSameString() {\r\n\t\tassertSame(firstnumber,secondnumber);\r\n\t\tassertNotSame(firstnumber,thirdnumber);\t\r\n\t  }\r\n}\r\n<\/pre>\n<ul>\n<li><strong>assertArrayEquals()<\/strong><\/li>\n<\/ul>\n<p>The assertArrayEquals() method checks whether two arrays are equal to each other or not. It will test number of elements in both the arrays, order of the elements and if the elements in the two arrays are the same. Here is a example.<\/p>\n<pre lang=\"java\">import static org.junit.Assert.*;\r\nimport org.junit.Test;\r\n\r\nimport java.util.Arrays;\r\n\r\npublic class Practice_codeTest {\r\n\r\n\t@Test\r\n\tpublic void testArrayEquals() {\r\n\t\tint[] numbers = {5,4,3,2,1};\r\n                \/\/Sorting array.\r\n\t\tArrays.sort(numbers);\r\n\t\tint[] expectedOutput = {1,2,3,4,5};\r\n                \/\/assertArrayEquals(\"expected array\",\"actual array\" );\r\n\t\tassertArrayEquals(expectedOutput, numbers);\r\n\t  }\r\n}\r\n<\/pre>\n<ul>\n<li><strong>assertThat()<\/strong><\/li>\n<\/ul>\n<p>The assertThat() methods satisfies the condition specified by matcher. A matcher is an object that implements the\u00a0<span style=\"text-decoration: underline;\">org.hamcrest.matcher<\/span>\u00a0interface. Hamcrest is a framework for writing matcher objects that allow me to declare rules for tests whether a given object matches the criteria or not. Matchers improve flexibility  and readability of the code. We can also define better failure messages. The Hamcrest library comes with numerous matchers included and also provides the facility to write your own Matcher. The most important Matchers of Hamcrest are the following:<br \/>\n<em>is, equalTo, not, containsString, allof, anyof, hasProperty,closeTo, greaterThan<\/em><br \/>\nThey all can be use by a static import of <span style=\"text-decoration: underline;\">org.hamcrest.CoreMatchers<\/span> .<br \/>\nHere is an example of some common matchers:<\/p>\n<pre lang=\"java\">\r\nimport static org.hamcrest.CoreMatchers.*;\r\nimport static org.junit.Assert.*;\r\nimport org.junit.Test;\r\n\r\npublic class TestFile {\r\n\t\r\n\t@Test\r\n\tpublic void MatchersExample() {\r\n\t    assertThat(123, is(123));\r\n\t    assertThat(\"book\", equalTo(\"book\"));\r\n\t    assertThat(\"book\", not(equalTo(\"apple\")));\r\n\t    assertThat(\"apple\", containsString(\"e\"));\r\n\t  }\r\n}\r\n<\/pre>\n<p><strong>Write Custom Matchers<\/strong><br \/>\nFor writing matchers I am going to create a new Class file <u>CustomMatchers.java<\/u> in the same package <u>junitMatchers<\/u> with my JUnit test file <u>TestFile.java<\/u> .<br \/>\nHere is my <u>CustomMatchers.java<\/u> in which i am creating a Custom Matcher <u>EvenNumber<\/u> ,which will check whether the number is even or not.<\/p>\n<pre lang=\"java\">\r\npackage junitMatchers;\r\n\r\nimport org.hamcrest.Description;\r\nimport org.hamcrest.Factory;\r\nimport org.hamcrest.Matcher;\r\nimport org.hamcrest.TypeSafeMatcher;\r\n\r\npublic class CustomMatchers extends TypeSafeMatcher<Integer> {\r\n\r\n  @Override\r\n  public boolean matchesSafely(Integer number) {\r\n\t  if (number % 2 != 0) {\r\n\t\t  return false;\r\n\t\t  }\r\n\treturn true;\r\n  }\r\n\r\n  public void describeTo(Description description) {\r\n    description.appendText(\"Given number is Even Number\");\r\n    \/\/ describe expectation.\r\n  }\r\n\r\n  @Factory\r\n  public static <T> Matcher<Integer> EvenNumber() {\r\n    return new CustomMatchers();\r\n  }\r\n}\r\n  <\/pre>\n<p>The @Override annotation is use to declare intent to override a method and @Factory annotation is allowing to manually create my test instances.<br \/>\nTo import this Matcher in my <u>TestFile.java<\/u> I will use this code:<\/p>\n<pre lang=\"java\">\r\nimport static junitMatchers.CustomMatchers.EvenNumber;\r\n<\/pre>\n<p>In this code junitMathers is Package name,CustomMatchers is Class File name and EvenNumber is the name of Matcher.<\/p>\n<p>Here is my complete <u>TestFile.java<\/u>,which is using Custom Matcher <u>EvenNumber<\/u> to test Actual number is even or not.<\/p>\n<pre lang=\"java\">\r\npackage junitMatchers;\r\n\r\nimport static junitMatchers.CustomMatchers.EvenNumber;\r\nimport static org.hamcrest.CoreMatchers.*;\r\nimport static org.junit.Assert.*;\r\nimport org.junit.Test;\r\n\r\npublic class TestFile {\r\n\t\r\n\t@Test\r\n\tpublic void testEvenNumber() {\r\n\t    assertThat(4, is(EvenNumber()));\r\n\t    assertThat(3, is(not(EvenNumber())));\r\n\t  }\r\n}\r\n<\/pre>\n<hr>\n<p>And that brings us to the end of the tutorial. Let us know if it helped having a beginner write for beginners. <\/p>\n","protected":false},"excerpt":{"rendered":"<p>Problem: JUnit tutorials are often written by testers with a reasonable amount of unit checking expertise Why this post? There are plenty of JUnit tutorials available online. They are often written by testers with a reasonable amount of unit checking experience. The problem is that experts and beginners see things differently. I began noticing that beginners often read these JUnit [&hellip;]<\/p>\n","protected":false},"author":5,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[53,54,66],"tags":[],"class_list":["post-1338","post","type-post","status-publish","format-standard","hentry","category-java","category-junit","category-unit-testing"],"_links":{"self":[{"href":"https:\/\/qxf2.com\/blog\/wp-json\/wp\/v2\/posts\/1338","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/qxf2.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/qxf2.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/qxf2.com\/blog\/wp-json\/wp\/v2\/users\/5"}],"replies":[{"embeddable":true,"href":"https:\/\/qxf2.com\/blog\/wp-json\/wp\/v2\/comments?post=1338"}],"version-history":[{"count":48,"href":"https:\/\/qxf2.com\/blog\/wp-json\/wp\/v2\/posts\/1338\/revisions"}],"predecessor-version":[{"id":1509,"href":"https:\/\/qxf2.com\/blog\/wp-json\/wp\/v2\/posts\/1338\/revisions\/1509"}],"wp:attachment":[{"href":"https:\/\/qxf2.com\/blog\/wp-json\/wp\/v2\/media?parent=1338"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/qxf2.com\/blog\/wp-json\/wp\/v2\/categories?post=1338"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/qxf2.com\/blog\/wp-json\/wp\/v2\/tags?post=1338"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}