{"id":32420,"date":"2023-03-27T12:48:21","date_gmt":"2023-03-27T19:48:21","guid":{"rendered":"https:\/\/coderpad.io\/?p=32420"},"modified":"2023-06-07T13:26:19","modified_gmt":"2023-06-07T20:26:19","slug":"how-to-use-assert-in-junit-with-examples","status":"publish","type":"post","link":"https:\/\/coderpad.io\/blog\/development\/how-to-use-assert-in-junit-with-examples\/","title":{"rendered":"How To Use Assert In JUnit With Examples"},"content":{"rendered":"\n<p>Assertions are at the heart of <a href=\"https:\/\/coderpad.io\/blog\/development\/integration-tests-vs-unit-tests-integration-matters-more\/\">unit testing<\/a>. They&#8217;re crucial in giving unit tests their &#8220;self-validating&#8221; characteristic, without which they&#8217;d be practically useless. In this post, you&#8217;ll learn more about the <code>Assert<\/code> JUnit class and how you can use it to write your assertions when unit testing your Java code.<\/p>\n\n\n\n<p>This will be a practical post, but we&#8217;ll start with a brief theoretical digression to explain what &#8220;assert&#8221; means in JUnit. Then, it&#8217;s time to roll up your sleeves. You&#8217;ll learn the following:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>The process for installing JUnit 5<\/li>\n\n\n\n<li>How to create a sample project for testing<\/li>\n\n\n\n<li>What the main assertion methods are and how they work<\/li>\n<\/ul>\n\n\n\n<p>Let&#8217;s get started.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><strong>What is <\/strong><strong><em>Assert <\/em><\/strong><strong>in JUnit?<\/strong><\/h2>\n\n\n\n<p>In JUnit, <code>Assert<\/code> is a class that contains many assertion methods you can use when writing unit tests. To understand what that means, you must take a step back and learn about the structure of unit tests first.<\/p>\n\n\n\n<p>Though this is far from being a rule, a unit test typically contains three phases:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>First, you prepare the values for your test.<\/li>\n\n\n\n<li>Then, you execute the action you want to test.<\/li>\n\n\n\n<li>Finally, you compare the results you got to what you expected to get.<\/li>\n<\/ul>\n\n\n\n<p>Unit test frameworks enable you to perform said comparisons by using assertions. An assertion is a type of special syntax you can use to express an expectation in your test code. If the expectation proves true, your test passes; otherwise, it fails. That&#8217;s why the structure above is known as the <em>arrange-act-assert<\/em> pattern.<\/p>\n\n\n\n<p>So, the JUnit <code>Assert<\/code> class is what allows you to write assertions in your JUnit tests. There are many assertions available; the main ones enable you to verify the following:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>The equality of two values<\/li>\n\n\n\n<li>Whether an object is <code>null<\/code><\/li>\n\n\n\n<li>The logical value of a boolean variable<\/li>\n\n\n\n<li>Whether two variables point to the same object in memory<\/li>\n<\/ul>\n\n\n\n<p>Let&#8217;s see how to use assertions in practice.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><strong>Installing JUnit 5 and creating a sample project<\/strong><\/h2>\n\n\n\n<p>Start by creating a new Java project and open it with the IDE or text editor you&#8217;re most comfortable with. The next step is to install JUnit 5 on your project. JUnit 5 is the latest major version of the framework, and it&#8217;s a complete rewrite. Rather than being a simple component, JUnit 5 is made up of several independent components. To be able to write tests, you need at least <em>JUnit Platform<\/em> and <em>JUnit Jupiter<\/em>. Since I&#8217;m using Maven, I&#8217;ll add the following to my <code>pom.xml<\/code> file:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-1\" data-shcb-language-name=\"HTML, XML\" data-shcb-language-slug=\"xml\"><span><code class=\"hljs language-xml shcb-wrap-lines\"><span class=\"hljs-tag\">&lt;<span class=\"hljs-name\">dependency<\/span>&gt;<\/span>\n\n<span class=\"hljs-tag\">&lt;<span class=\"hljs-name\">groupId<\/span>&gt;<\/span>org.junit.jupiter<span class=\"hljs-tag\">&lt;\/<span class=\"hljs-name\">groupId<\/span>&gt;<\/span>\n\n<span class=\"hljs-tag\">&lt;<span class=\"hljs-name\">artifactId<\/span>&gt;<\/span>junit-jupiter-engine<span class=\"hljs-tag\">&lt;\/<span class=\"hljs-name\">artifactId<\/span>&gt;<\/span>\n\n<span class=\"hljs-tag\">&lt;<span class=\"hljs-name\">version<\/span>&gt;<\/span>5.2.0<span class=\"hljs-tag\">&lt;\/<span class=\"hljs-name\">version<\/span>&gt;<\/span>\n\n<span class=\"hljs-tag\">&lt;<span class=\"hljs-name\">scope<\/span>&gt;<\/span>test<span class=\"hljs-tag\">&lt;\/<span class=\"hljs-name\">scope<\/span>&gt;<\/span>\n\n<span class=\"hljs-tag\">&lt;\/<span class=\"hljs-name\">dependency<\/span>&gt;<\/span>\n\n<span class=\"hljs-tag\">&lt;<span class=\"hljs-name\">dependency<\/span>&gt;<\/span>\n\n<span class=\"hljs-tag\">&lt;<span class=\"hljs-name\">groupId<\/span>&gt;<\/span>org.junit.platform<span class=\"hljs-tag\">&lt;\/<span class=\"hljs-name\">groupId<\/span>&gt;<\/span>\n\n<span class=\"hljs-tag\">&lt;<span class=\"hljs-name\">artifactId<\/span>&gt;<\/span>junit-platform-runner<span class=\"hljs-tag\">&lt;\/<span class=\"hljs-name\">artifactId<\/span>&gt;<\/span>\n\n<span class=\"hljs-tag\">&lt;<span class=\"hljs-name\">version<\/span>&gt;<\/span>1.2.0<span class=\"hljs-tag\">&lt;\/<span class=\"hljs-name\">version<\/span>&gt;<\/span>\n\n<span class=\"hljs-tag\">&lt;<span class=\"hljs-name\">scope<\/span>&gt;<\/span>test<span class=\"hljs-tag\">&lt;\/<span class=\"hljs-name\">scope<\/span>&gt;<\/span>\n\n<span class=\"hljs-tag\">&lt;\/<span class=\"hljs-name\">dependency<\/span>&gt;<\/span><\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-1\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">HTML, XML<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">xml<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>Now, go under <code>src\/test\/java<\/code> and create a new Java class. Call it <code>DemoTest<\/code> and paste the following code on it:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-2\" data-shcb-language-name=\"Java\" data-shcb-language-slug=\"java\"><span><code class=\"hljs language-java shcb-wrap-lines\"><span class=\"hljs-keyword\">import<\/span> org.junit.Test;\n\n<span class=\"hljs-keyword\">import<\/span> <span class=\"hljs-keyword\">static<\/span> org.junit.Assert.*;\n\n<span class=\"hljs-keyword\">public<\/span> <span class=\"hljs-class\"><span class=\"hljs-keyword\">class<\/span> <span class=\"hljs-title\">DemoTest<\/span> <\/span>{\n\n}<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-2\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Java<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">java<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<h2 class=\"wp-block-heading\"><strong>The main JUnit <\/strong><strong><em>Assert m<\/em><\/strong><strong>ethods<\/strong><\/h2>\n\n\n\n<p>With your demo project in place, it&#8217;s time to start writing some assertions.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>assertEquals()<\/strong><\/h3>\n\n\n\n<p><code>assertEquals()<\/code> is probably the most used assertion. With it, you can compare two values and see whether they&#8217;re equal. Here&#8217;s an example of <code>assertEquals()<\/code> that uses two overloads of the method, one for integers and the other for strings:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-3\" data-shcb-language-name=\"Java\" data-shcb-language-slug=\"java\"><span><code class=\"hljs language-java shcb-wrap-lines\"><span class=\"hljs-meta\">@Test<\/span>\n    <span class=\"hljs-function\"><span class=\"hljs-keyword\">public<\/span> <span class=\"hljs-keyword\">void<\/span> <span class=\"hljs-title\">assertEquals_demo<\/span><span class=\"hljs-params\">()<\/span> <\/span>{\n        <span class=\"hljs-comment\">\/\/ integers<\/span>\n        <span class=\"hljs-keyword\">int<\/span> expected = <span class=\"hljs-number\">4<\/span>;\n        <span class=\"hljs-keyword\">int<\/span> actual = <span class=\"hljs-number\">2<\/span> + <span class=\"hljs-number\">2<\/span>;\n        assertEquals(expected, actual);\n\n\n        <span class=\"hljs-comment\">\/\/ strings<\/span>\n        assertEquals(<span class=\"hljs-string\">\"JUnit5\"<\/span>, <span class=\"hljs-string\">\"JUnit\"<\/span> + <span class=\"hljs-string\">\"5\"<\/span>);\n    }\n<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-3\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Java<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">java<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>Generally speaking, you should avoid more than one assertion per test method, but this is just an example here.&nbsp;<\/p>\n\n\n\n<p>Also, remember that <strong>argument order matters when using<\/strong> <code>assertEquals()<\/code>. The first argument represents the result you expect to get after the &#8220;act&#8221; phase of your test, and the second one is what you actually got. Those values are then used in the error message when the test fails, so mixing them up can throw off your test results<\/p>\n\n\n\n<p>Let&#8217;s see a test failure example. I&#8217;ll go back to the previous example, and in the line where I assign the expected variable, I&#8217;ll pass 5 to it instead of 4. When I run the test, I get this result:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-4\" data-shcb-language-name=\"CSS\" data-shcb-language-slug=\"css\"><span><code class=\"hljs language-css shcb-wrap-lines\"><span class=\"hljs-selector-tag\">java<\/span><span class=\"hljs-selector-class\">.lang<\/span><span class=\"hljs-selector-class\">.AssertionError<\/span>:\u00a0\n\n<span class=\"hljs-selector-tag\">Expected<\/span>: 5\n\n<span class=\"hljs-selector-tag\">Actual<\/span>: 4<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-4\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">CSS<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">css<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<h4 class=\"wp-block-heading\"><strong>A warning on reference types<\/strong><\/h4>\n\n\n\n<p>Before moving on, there&#8217;s something you need to be aware of when dealing with reference types. For that, consider a simple class:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-5\" data-shcb-language-name=\"Java\" data-shcb-language-slug=\"java\"><span><code class=\"hljs language-java shcb-wrap-lines\"><span class=\"hljs-keyword\">public<\/span> <span class=\"hljs-class\"><span class=\"hljs-keyword\">class<\/span> <span class=\"hljs-title\">Person<\/span> <\/span>{\n\n\u00a0\u00a0\u00a0\u00a0<span class=\"hljs-keyword\">private<\/span> <span class=\"hljs-keyword\">final<\/span> String name;\n\n\u00a0\u00a0\u00a0\u00a0<span class=\"hljs-keyword\">private<\/span> <span class=\"hljs-keyword\">final<\/span> <span class=\"hljs-keyword\">int<\/span> age;\n\n\u00a0\u00a0\u00a0\u00a0<span class=\"hljs-function\"><span class=\"hljs-keyword\">public<\/span> <span class=\"hljs-title\">Person<\/span><span class=\"hljs-params\">(String name, <span class=\"hljs-keyword\">int<\/span> age)<\/span> <\/span>{\n\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0<span class=\"hljs-keyword\">this<\/span>.name = name;\n\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0<span class=\"hljs-keyword\">this<\/span>.age = age;\n\n\u00a0\u00a0\u00a0\u00a0}\n\n}<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-5\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Java<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">java<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>Now, consider the following test:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-6\" data-shcb-language-name=\"Java\" data-shcb-language-slug=\"java\"><span><code class=\"hljs language-java shcb-wrap-lines\">p1 = <span class=\"hljs-keyword\">new<\/span> Person(<span class=\"hljs-string\">\"John Doe\"<\/span>, <span class=\"hljs-number\">32<\/span>);\n\n<span class=\"hljs-keyword\">var<\/span> p2 = <span class=\"hljs-keyword\">new<\/span> Person(<span class=\"hljs-string\">\"John Doe\"<\/span>, <span class=\"hljs-number\">32<\/span>);\n\nassertEquals(p1, p2);<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-6\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Java<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">java<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>You might think that such a test would pass, but it fails:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-7\" data-shcb-language-name=\"CSS\" data-shcb-language-slug=\"css\"><span><code class=\"hljs language-css shcb-wrap-lines\"><span class=\"hljs-selector-tag\">java<\/span><span class=\"hljs-selector-class\">.lang<\/span><span class=\"hljs-selector-class\">.AssertionError<\/span>:\u00a0\n\n<span class=\"hljs-selector-tag\">Expected<\/span> <span class=\"hljs-selector-pseudo\">:Person<\/span><span class=\"hljs-keyword\">@17d99928<\/span>\n\nActual \u00a0 :Person@<span class=\"hljs-number\">3834<\/span>d63f\n\n&lt;Click to see difference&gt;<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-7\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">CSS<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">css<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>That&#8217;s because classes are <a href=\"https:\/\/www.javatpoint.com\/reference-data-types-in-java\" target=\"_blank\" rel=\"noopener\">reference types<\/a>. As such, when you use <code>assertEquals<\/code>, only the references of the objects are compared by default. Even though <code>p1<\/code> and <code>p2<\/code> have the same values, they refer to different objects in the heap memory, so they&#8217;re considered different.<\/p>\n\n\n\n<p>However, we really want to compare those two objects by their values, not their references. In other words, we want <em>structural equality<\/em> rather than <em>referential equality<\/em>. Achieving that is easy: you&#8217;d have to override the <code>equals()<\/code> method on the <code>Person<\/code> class.<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-8\" data-shcb-language-name=\"Java\" data-shcb-language-slug=\"java\"><span><code class=\"hljs language-java shcb-wrap-lines\"><span class=\"hljs-meta\">@Override<\/span>\n\n<span class=\"hljs-function\"><span class=\"hljs-keyword\">public<\/span> <span class=\"hljs-keyword\">boolean<\/span> <span class=\"hljs-title\">equals<\/span><span class=\"hljs-params\">(Object obj)<\/span> <\/span>{\n\n<span class=\"hljs-keyword\">if<\/span> (obj == <span class=\"hljs-keyword\">this<\/span>)\n\n<span class=\"hljs-keyword\">return<\/span> <span class=\"hljs-keyword\">true<\/span>;\n\n<span class=\"hljs-keyword\">if<\/span> (!(obj <span class=\"hljs-keyword\">instanceof<\/span> Person)) {\n\n<span class=\"hljs-keyword\">return<\/span> <span class=\"hljs-keyword\">false<\/span>;\n\n}\n\nPerson other = (Person) obj;\n\n<span class=\"hljs-keyword\">return<\/span> other.name.equals(<span class=\"hljs-keyword\">this<\/span>.name) &amp;&amp; other.age == <span class=\"hljs-keyword\">this<\/span>.age;\n\n}<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-8\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Java<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">java<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<h4 class=\"wp-block-heading\"><strong>A useful overload<\/strong><\/h4>\n\n\n\n<p>There are multiple versions (overloads) of the <code>assertEquals()<\/code> method that can be used with different data types such as <code>long<\/code><strong>, <\/strong><code>String<\/code><strong>, <\/strong><code>double<\/code>, <code>float<\/code><strong>, <\/strong><code>int<\/code>, etc. Each of these versions also has a variant that includes an additional <code>String<\/code> parameter called <code>message<\/code>. This variant can be used to specify a message to be displayed if the test fails. This can be useful when multiple tests fail simultaneously, as it allows for faster identification of the issue.<\/p>\n\n\n\n<p>By the way, all assertion methods have an overload like that. So it&#8217;d be redundant to provide an example for each. You&#8217;ll see an example of the<strong> <\/strong><code>message<\/code> parameter being used soon.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>assertNotEquals()<\/strong><\/h3>\n\n\n\n<p>It&#8217;s common for assertion methods to have an inverse method. <code>assertNotEquals()<\/code> asserts that two objects are different. Like its counterpart, you should pay attention to the order of the parameters:&nbsp;<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>First comes the unexpected value<\/li>\n\n\n\n<li>Then the actual value<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>assertTrue()<\/strong><\/h3>\n\n\n\n<p>The <code>assertTrue()<\/code> method asserts that a given boolean value is true. As an example, let&#8217;s rewrite the previous assertion, replacing <code>assertEquals<\/code> with <code>assertTrue<\/code>:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-9\" data-shcb-language-name=\"Java\" data-shcb-language-slug=\"java\"><span><code class=\"hljs language-java shcb-wrap-lines\">assertTrue(p1.equals(p2));<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-9\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Java<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">java<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>This is just an example. In real test code, it\u2019s better to use <code>assertEquals<\/code> over<strong> <\/strong><code>assertTrue<\/code> when comparing two values. That&#8217;s because <code>assertEquals<\/code> will give you a more useful error message when a failure occurs, following the pattern &#8220;expected: x; actual: y.&#8221;<\/p>\n\n\n\n<p>Use <code>assertTrue()<\/code>, for instance, to assert the return value of a method of type boolean. Here&#8217;s an example:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-10\" data-shcb-language-name=\"Java\" data-shcb-language-slug=\"java\"><span><code class=\"hljs language-java shcb-wrap-lines\"><span class=\"hljs-meta\">@Test<\/span>\n<span class=\"hljs-function\"><span class=\"hljs-keyword\">public<\/span> <span class=\"hljs-keyword\">void<\/span> <span class=\"hljs-title\">assertTrue_demo<\/span><span class=\"hljs-params\">()<\/span> <\/span>{\n\t<span class=\"hljs-keyword\">int<\/span> yearsOfEmployment = <span class=\"hljs-number\">5<\/span>;\n\tString name = <span class=\"hljs-string\">\"John Doe\"<\/span>;\n\tEmployee emp = <span class=\"hljs-keyword\">new<\/span> Employee(name, yearsOfEmployment);\n\tassertTrue(emp.isEligibleForSabbatical());\n}<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-10\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Java<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">java<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>This is the code for the<strong> <\/strong><code>Employee<\/code> class:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-11\" data-shcb-language-name=\"Java\" data-shcb-language-slug=\"java\"><span><code class=\"hljs language-java shcb-wrap-lines\"><span class=\"hljs-keyword\">public<\/span> <span class=\"hljs-class\"><span class=\"hljs-keyword\">class<\/span> <span class=\"hljs-title\">Employee<\/span> <\/span>{\n\n\u00a0\u00a0\u00a0\u00a0<span class=\"hljs-keyword\">private<\/span> <span class=\"hljs-keyword\">final<\/span> String name;\n\n\u00a0\u00a0\u00a0\u00a0<span class=\"hljs-keyword\">private<\/span> <span class=\"hljs-keyword\">final<\/span> <span class=\"hljs-keyword\">int<\/span> yearsOfEmployment;\n\n\u00a0\u00a0\u00a0\u00a0<span class=\"hljs-function\"><span class=\"hljs-keyword\">public<\/span> <span class=\"hljs-title\">Employee<\/span><span class=\"hljs-params\">(String name, <span class=\"hljs-keyword\">int<\/span> yearsOfEmployment)<\/span> <\/span>{\n\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0<span class=\"hljs-keyword\">this<\/span>.name = name;\n\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0<span class=\"hljs-keyword\">this<\/span>.yearsOfEmployment = yearsOfEmployment;\n\n\u00a0\u00a0\u00a0\u00a0}\n\n\u00a0\u00a0\u00a0\u00a0<span class=\"hljs-function\"><span class=\"hljs-keyword\">public<\/span> <span class=\"hljs-keyword\">boolean<\/span> <span class=\"hljs-title\">isEligibleForSabbatical<\/span><span class=\"hljs-params\">()<\/span> <\/span>{\n\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0<span class=\"hljs-keyword\">return<\/span> yearsOfEmployment &gt;= <span class=\"hljs-number\">5<\/span>;\n\n\u00a0\u00a0\u00a0\u00a0}\n\n}<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-11\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Java<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">java<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p><code>assertTrue()<\/code> has a useful overload in which you can provide a message when the test fails:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-12\" data-shcb-language-name=\"Java\" data-shcb-language-slug=\"java\"><span><code class=\"hljs language-java shcb-wrap-lines\"><span class=\"hljs-meta\">@Test<\/span>\n<span class=\"hljs-function\"><span class=\"hljs-keyword\">public<\/span> <span class=\"hljs-keyword\">void<\/span> <span class=\"hljs-title\">assertTrue_demo<\/span><span class=\"hljs-params\">()<\/span> <\/span>{\n\t<span class=\"hljs-keyword\">int<\/span> yearsOfEmployment = <span class=\"hljs-number\">5<\/span>;\n\tString name = <span class=\"hljs-string\">\"John Doe\"<\/span>;\n\tEmployee emp = <span class=\"hljs-keyword\">new<\/span> Employee(name, yearsOfEmployment);\n\tassertTrue(\n\t\t\t<span class=\"hljs-string\">\"Employees with 5 or more years of employment are eligible for a sabbatical\"<\/span>,\n\t\t\temp.isEligibleForSabbatical());\n}<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-12\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Java<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">java<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>I&#8217;ll go into the production method and add a bug:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-13\" data-shcb-language-name=\"Java\" data-shcb-language-slug=\"java\"><span><code class=\"hljs language-java shcb-wrap-lines\"><span class=\"hljs-keyword\">return<\/span> yearsOfEmployment &gt;= <span class=\"hljs-number\">6<\/span>;<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-13\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Java<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">java<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>Now the test fails with a helpful message:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-14\" data-shcb-language-name=\"CSS\" data-shcb-language-slug=\"css\"><span><code class=\"hljs language-css shcb-wrap-lines\"><span class=\"hljs-selector-tag\">java<\/span><span class=\"hljs-selector-class\">.lang<\/span><span class=\"hljs-selector-class\">.AssertionError<\/span>: <span class=\"hljs-selector-tag\">Employees<\/span> <span class=\"hljs-selector-tag\">with<\/span> 5 <span class=\"hljs-selector-tag\">or<\/span> <span class=\"hljs-selector-tag\">more<\/span> <span class=\"hljs-selector-tag\">years<\/span> <span class=\"hljs-selector-tag\">of<\/span> <span class=\"hljs-selector-tag\">employment<\/span> <span class=\"hljs-selector-tag\">are<\/span> <span class=\"hljs-selector-tag\">eligible<\/span> <span class=\"hljs-selector-tag\">for<\/span> <span class=\"hljs-selector-tag\">a<\/span> <span class=\"hljs-selector-tag\">sabbatical<\/span>\n\n<span class=\"hljs-selector-tag\">at<\/span> <span class=\"hljs-selector-tag\">org<\/span><span class=\"hljs-selector-class\">.junit<\/span><span class=\"hljs-selector-class\">.Assert<\/span><span class=\"hljs-selector-class\">.fail<\/span>(<span class=\"hljs-selector-tag\">Assert<\/span><span class=\"hljs-selector-class\">.java<\/span><span class=\"hljs-selector-pseudo\">:89)<\/span>\n\n<span class=\"hljs-selector-tag\">at<\/span> <span class=\"hljs-selector-tag\">org<\/span><span class=\"hljs-selector-class\">.junit<\/span><span class=\"hljs-selector-class\">.Assert<\/span><span class=\"hljs-selector-class\">.assertTrue<\/span>(<span class=\"hljs-selector-tag\">Assert<\/span><span class=\"hljs-selector-class\">.java<\/span><span class=\"hljs-selector-pseudo\">:42)<\/span>\n\n<span class=\"hljs-selector-tag\">at<\/span> <span class=\"hljs-selector-tag\">DemoTest<\/span><span class=\"hljs-selector-class\">.assertTrue_demo<\/span>(<span class=\"hljs-selector-tag\">DemoTest<\/span><span class=\"hljs-selector-class\">.java<\/span><span class=\"hljs-selector-pseudo\">:10)<\/span>\n\n<span class=\"hljs-selector-attr\">&#91;...]<\/span><\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-14\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">CSS<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">css<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<h3 class=\"wp-block-heading\"><strong>assertFalse()<\/strong><\/h3>\n\n\n\n<p>As its name suggests, the <code>assertFalse()<\/code> method is the opposite of <code>assertTrue()<\/code> \u2013 the test passes when its parameter evaluates to false.&nbsp;<\/p>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>assertSame()<\/strong><\/h3>\n\n\n\n<p>When discussing <code>assertEquals()<\/code>, you&#8217;ve learned that reference types (objects) are compared regarding their references. That&#8217;s why<strong> <\/strong><code>assertEquals()<\/code><strong> <\/strong>fails for objects that don&#8217;t override the <code>equals()<\/code> method. What if you really wanted to verify reference equality? In this case, you&#8217;d use the <code>assertSame()<\/code> method:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-15\" data-shcb-language-name=\"Java\" data-shcb-language-slug=\"java\"><span><code class=\"hljs language-java shcb-wrap-lines\"><span class=\"hljs-keyword\">var<\/span> p1 = <span class=\"hljs-keyword\">new<\/span> Person(<span class=\"hljs-string\">\"Jane Doe\"<\/span>, <span class=\"hljs-number\">20<\/span>);\n\n<span class=\"hljs-keyword\">var<\/span> p2 = p1;\n\nassertSame(p1, p2);<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-15\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Java<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">java<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<h3 class=\"wp-block-heading\"><strong>assertNotSame()<\/strong><\/h3>\n\n\n\n<p>If you wanted to assert that two variables don&#8217;t point to the same object, you&#8217;d use the opposite method: <code>assertNotSame()<\/code>.&nbsp;<\/p>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>assertNull()<\/strong><\/h3>\n\n\n\n<p>You use the <code>assertNull()<\/code> method to verify whether the specified parameter contains a <code>null<\/code> reference:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-16\" data-shcb-language-name=\"Java\" data-shcb-language-slug=\"java\"><span><code class=\"hljs language-java shcb-wrap-lines\">PhoneNumber candidate = PhoneNumber.tryParse(<span class=\"hljs-string\">\"this isn't a phone number\"<\/span>);\nassertNull(candidate);<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-16\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Java<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">java<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<h3 class=\"wp-block-heading\"><strong>assertNotNull()<\/strong><\/h3>\n\n\n\n<p>You should know the drill by now: this is the inverse of the previous one, and I won&#8217;t bore you with an example.&nbsp;<\/p>\n\n\n\n<p>Just a personal anecdote: I rarely use <code>assertNotNull()<\/code> when writing my tests. Most of the time, I find that there are more useful assertions I can write. For instance, I often have a specific value I want to compare the result of the operation to, in which case <code>assertEquals()<\/code> is the answer.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>assertThrows()<\/strong><\/h3>\n\n\n\n<p>When writing tests, not only must you test the scenario in which everything works fine\u2014i.e. the happy path\u2014but you should also test the sad path scenarios.<\/p>\n\n\n\n<p>Languages like Java use the concept of exceptions to express unintended behaviors and errors in methods. So you&#8217;ll often have to write tests that verify whether a given exception happens.<\/p>\n\n\n\n<p>Let&#8217;s go back to the <code>Person<\/code> class from previous examples and change its constructor, adding two <a href=\"https:\/\/wiki.c2.com\/?GuardClause\" target=\"_blank\" rel=\"noopener\">guard clauses<\/a>:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-17\" data-shcb-language-name=\"Java\" data-shcb-language-slug=\"java\"><span><code class=\"hljs language-java shcb-wrap-lines\"><span class=\"hljs-function\"><span class=\"hljs-keyword\">public<\/span> <span class=\"hljs-title\">Person<\/span><span class=\"hljs-params\">(String name, <span class=\"hljs-keyword\">int<\/span> age)<\/span> <\/span>{\n\t<span class=\"hljs-keyword\">if<\/span> (name == <span class=\"hljs-keyword\">null<\/span> || name.trim().isEmpty())\n\t\t<span class=\"hljs-keyword\">throw<\/span> <span class=\"hljs-keyword\">new<\/span> IllegalArgumentException(<span class=\"hljs-string\">\"Name shouldn't be empty!\"<\/span>);\n\n\n\t<span class=\"hljs-keyword\">if<\/span> (age &lt; <span class=\"hljs-number\">0<\/span>)\n\t\t<span class=\"hljs-keyword\">throw<\/span> <span class=\"hljs-keyword\">new<\/span> IllegalArgumentException(<span class=\"hljs-string\">\"Age can't be negative!\"<\/span>);\n\n\n\t<span class=\"hljs-keyword\">this<\/span>.name = name;\n\t<span class=\"hljs-keyword\">this<\/span>.age = age;\n}<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-17\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Java<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">java<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>You&#8217;ll agree with me that it&#8217;s reasonable to prohibit empty names and negative ages. But now it&#8217;d be great to have tests for these scenarios for two reasons:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><em>Documentation<\/em>: The tests will serve as a specification of the class&#8217;s behavior.<\/li>\n\n\n\n<li><em>Code quality<\/em>: The tests will prevent the guard clauses from being removed or changed.<\/li>\n<\/ul>\n\n\n\n<p>Let&#8217;s write a test for the negative age scenario:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-18\" data-shcb-language-name=\"Java\" data-shcb-language-slug=\"java\"><span><code class=\"hljs language-java shcb-wrap-lines\"><span class=\"hljs-meta\">@Test<\/span>\n<span class=\"hljs-function\"><span class=\"hljs-keyword\">public<\/span> <span class=\"hljs-keyword\">void<\/span> <span class=\"hljs-title\">negativeAgesNotAllowed<\/span><span class=\"hljs-params\">()<\/span> <\/span>{\n\t<span class=\"hljs-keyword\">int<\/span> age = -<span class=\"hljs-number\">1<\/span>;\n\tString name = <span class=\"hljs-string\">\"John Doe\"<\/span>;\n\tassertThrows(IllegalArgumentException<span class=\"hljs-class\">.<span class=\"hljs-keyword\">class<\/span>, () -&gt; <span class=\"hljs-title\">new<\/span> <span class=\"hljs-title\">Person<\/span>(<span class=\"hljs-title\">name<\/span>, <span class=\"hljs-title\">age<\/span>))<\/span>;\n}<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-18\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Java<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">java<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>As you can see, using <code>assertThrows<\/code> isn&#8217;t hard: you pass the expected exception class as the first argument and a lambda expression representing the action to be executed as the second one.&nbsp;<\/p>\n\n\n\n<p>As an exercise, try implementing tests for these scenarios for the <code>name<\/code> argument:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>An empty string<\/li>\n\n\n\n<li>A string with spaces<\/li>\n\n\n\n<li><code>null<\/code><\/li>\n<\/ul>\n\n\n\n<p>How about you try out JUnit in the sandbox below?<\/p>\n\n\n<div\n\tclass=\"sandbox-embed responsive-embed \"\n\tstyle=\"padding-top: 85%\"\ndata-block-name=\"coderpad-sandbox-embed\">\n\t<iframe src=\"https:\/\/embed.coderpad.io\/sandbox?question_id=246060&#038;use_question_button\" width=\"640\" height=\"544\" loading=\"lazy\" aria-label=\"Try out the CoderPad sandbox\"><\/iframe>\n<\/div>\n\n\n\n<h2 class=\"wp-block-heading\"><strong><em>Assert y<\/em><\/strong><strong>our way to better software<\/strong><\/h2>\n\n\n\n<p>In this post, you&#8217;ve learned what assertions are, why they&#8217;re crucial for unit testing, and how to write assertions using the JUnit <code>Assert<\/code> class.<\/p>\n\n\n\n<p>Where should you go next? My suggestion is for you to explore the<strong> <\/strong><code>Assert<\/code> class in more depth. There are many assertions available. The ones we&#8217;ve explored barely scratch the surface, despite being some of the most important ones. The more you master the <code>Assert<\/code>&nbsp;class, the more expressive your unit tests will be.<\/p>\n\n\n\n<p>Thanks for reading!<\/p>\n\n\n\n<p><em>This post was written by <\/em><em>Carlos Schults. <\/em><a href=\"https:\/\/carlosschults.net\" target=\"_blank\" rel=\"noopener\"><em>Carlos<\/em><\/a><em> is a consultant and software engineer with experience in desktop, web, and mobile development. Though his primary language is C#, he has experience with a number of languages and platforms. His main interests include automated testing, version control, and code quality.&nbsp;<\/em><\/p>\n","protected":false},"excerpt":{"rendered":"<p>The JUnit Assert class is what you use to write unit testing assertions in JUnit. Learn more about it in this guide, full of examples.<\/p>\n","protected":false},"author":1,"featured_media":32851,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"_acf_changed":false,"footnotes":""},"categories":[9],"tags":[],"persona":[29],"blog-programming-language":[51],"keyword-cluster":[],"class_list":["post-32420","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-development"],"acf":[],"_links":{"self":[{"href":"https:\/\/coderpad.io\/wp-json\/wp\/v2\/posts\/32420","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/coderpad.io\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/coderpad.io\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/coderpad.io\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/coderpad.io\/wp-json\/wp\/v2\/comments?post=32420"}],"version-history":[{"count":75,"href":"https:\/\/coderpad.io\/wp-json\/wp\/v2\/posts\/32420\/revisions"}],"predecessor-version":[{"id":34536,"href":"https:\/\/coderpad.io\/wp-json\/wp\/v2\/posts\/32420\/revisions\/34536"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/coderpad.io\/wp-json\/wp\/v2\/media\/32851"}],"wp:attachment":[{"href":"https:\/\/coderpad.io\/wp-json\/wp\/v2\/media?parent=32420"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/coderpad.io\/wp-json\/wp\/v2\/categories?post=32420"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/coderpad.io\/wp-json\/wp\/v2\/tags?post=32420"},{"taxonomy":"persona","embeddable":true,"href":"https:\/\/coderpad.io\/wp-json\/wp\/v2\/persona?post=32420"},{"taxonomy":"blog-programming-language","embeddable":true,"href":"https:\/\/coderpad.io\/wp-json\/wp\/v2\/blog-programming-language?post=32420"},{"taxonomy":"keyword-cluster","embeddable":true,"href":"https:\/\/coderpad.io\/wp-json\/wp\/v2\/keyword-cluster?post=32420"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}