{"id":3370,"date":"2024-03-26T08:29:11","date_gmt":"2024-03-26T12:29:11","guid":{"rendered":"https:\/\/www.yorku.ca\/professor\/drsmith\/?p=3370"},"modified":"2024-03-26T08:29:36","modified_gmt":"2024-03-26T12:29:36","slug":"unit-testing-for-a-project-in-java","status":"publish","type":"post","link":"https:\/\/www.yorku.ca\/professor\/drsmith\/2024\/03\/26\/unit-testing-for-a-project-in-java\/","title":{"rendered":"Unit testing for a project in Java"},"content":{"rendered":"\n<p>It's important to create test frameworks for your programs.  In Java we use the jUnit system to do so.  Here is an example of setting up a unit tester to make sure that that a method returns the values it's supposed to.<\/p>\n\n\n\n<p>First, let's look at the method.  I'm using it to convert values that are bounded from 0 to 1023 into values from 0 to 100.  I do this before graphing the results.  The class is called GraphPeriodicUpdate.  The method is called normalizeValue.  It takes an integer and returns an integer:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code><span class=\"has-inline-color has-vivid-green-cyan-color\">    \/\/ Conversion of sensor values from 0 to 1023 into 0 to 100;\n<\/span>    static public int <strong>normalizeYValue<\/strong>(int originalValue){\n\n        final float MAXVALUE = 1023.0F;\n        final float MINVALUE = 0.0F;\n        final int ERRORVALUE = -1000;\n\n\n        int theReturnValue;\n\n        if((originalValue &gt; MAXVALUE)){\n            theReturnValue = ERRORVALUE;\n        }\n        else if ( (originalValue &lt; MINVALUE) ){\n            theReturnValue = ERRORVALUE;\n        }\n        else{\n            theReturnValue = (int)(100.0*((float)(originalValue)*((1.0)\/(MAXVALUE-MINVALUE))));\n        }\n        return theReturnValue;\n    }<\/code><\/pre>\n\n\n\n<p>The method is designed to return -1000 if the inputs are outside of the 0 to 1023 boundaries.  Now, my unit tester should ensure that <\/p>\n\n\n\n<ol class=\"wp-block-list\"><li>the method returns the -1000 error value when faced with inputs that are less than 0 or greater than 1023, and<\/li><li>the method only returns values from 0 to 100 if the inputs are 0 to 1023.<\/li><\/ol>\n\n\n\n<p>Here's how I can do that:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>import org.junit.Test;\n\nimport static org.junit.Assert.assertEquals;\nimport static org.junit.Assert.assertTrue;\nimport java.util.Random;\n\npublic class theUnitTest {\n    final int MAXINPUT = 1023;\n    final int MININPUT = 0;\n    final int ERRORVALUE = -1000;\n\n    final int MINRESULT = 0;\n    final int MAXRESULT = 100;\n\n<span class=\"has-inline-color has-luminous-vivid-orange-color\">    @Test\n<\/span>    public void <strong>testTheGraphNormalizingMethod<\/strong>(){\n\n<span class=\"has-inline-color has-vivid-green-cyan-color\">        \/\/ test to make sure that -1000 is returned for values above 1023 ...\n<\/span>        System.out.println(<span class=\"has-inline-color has-pale-pink-color\">\"Testing against too positive input...that it returns an error value of \"<\/span> + ERRORVALUE);\n        String theErrorMessage0 = <span class=\"has-inline-color has-pale-pink-color\">\"Error: wrong value returned for an input above 1023.\"<\/span>;\n        <span class=\"has-inline-color has-vivid-cyan-blue-color\">assertEquals<\/span>(theErrorMessage0, ERRORVALUE,GraphPeriodicUpdate.normalizeYValue(MAXINPUT+1));\n        <span class=\"has-inline-color has-vivid-cyan-blue-color\">assertEquals<\/span>(theErrorMessage0, ERRORVALUE,GraphPeriodicUpdate.normalizeYValue(MAXINPUT*1000));\n\n<span class=\"has-inline-color has-vivid-green-cyan-color\">        \/\/ ... or below 0.\n<\/span>        System.out.println(<span class=\"has-inline-color has-pale-pink-color\">\"Testing against too negative input... that it returns an error value of \"<\/span> + ERRORVALUE);\n        String theErrorMessage1 = <span class=\"has-inline-color has-pale-pink-color\">\"Error: wrong value returned for an input below 0.\"<\/span>;\n        <span class=\"has-inline-color has-vivid-cyan-blue-color\">assertEquals<\/span>(theErrorMessage1, ERRORVALUE,GraphPeriodicUpdate.normalizeYValue(MININPUT-1));\n        <span class=\"has-inline-color has-vivid-cyan-blue-color\">assertEquals<\/span>(theErrorMessage1, ERRORVALUE,GraphPeriodicUpdate.normalizeYValue((MININPUT-1)*1000));\n\n<span class=\"has-inline-color has-vivid-green-cyan-color\">        \/\/ TESt to see how it behaves for values from 0 to 1023\n        \/\/ if there's a problem, print a message saying so.<\/span>\n        System.out.println(<span class=\"has-inline-color has-pale-pink-color\">\"Testing against values from \"<\/span> + MININPUT + <span class=\"has-inline-color has-pale-pink-color\">\" to \"<\/span> + MAXINPUT);\n        int theResult;\n        theResult = GraphPeriodicUpdate.normalizeYValue(MININPUT);\n        String theErrorMessage2 = <span class=\"has-inline-color has-pale-pink-color\">\"Error: The result shouldn't be below 0\"<\/span>;  <span class=\"has-inline-color has-vivid-green-cyan-color\">\/\/ show this if the test fails.<\/span>\n        <span class=\"has-inline-color has-vivid-cyan-blue-color\">assertTrue<\/span>(theErrorMessage2, theResult &gt;= MINRESULT);\n\n        theResult = GraphPeriodicUpdate.normalizeYValue(MAXINPUT+1);\n        String theErrorMessage3 = <span class=\"has-inline-color has-pale-pink-color\">\"Error: The result shouldn't be above 100<\/span>\"; <span class=\"has-inline-color has-vivid-green-cyan-color\">\/\/ show this if the test fails.<\/span>\n        <span class=\"has-inline-color has-vivid-cyan-blue-color\">assertTrue<\/span>(theErrorMessage3, theResult &lt;= MAXRESULT);\n\n<span class=\"has-inline-color has-vivid-green-cyan-color\">        \/\/ Throw at it a hundred random numbers, bounded from min to max values, to see if it fails...\n<\/span>        for (int i = 0; i &lt; 100; i++) {\n                System.out.print(<span class=\"has-inline-color has-pale-pink-color\">\".<\/span>\");\n                Random randomObject = new Random();\n                int randValue = randomObject.nextInt(MAXINPUT+1);\n                theResult = GraphPeriodicUpdate.normalizeYValue(randValue);\n                String theErrorMessage4 =<span class=\"has-inline-color has-pale-pink-color\">\"Error: The result is _not_ between 0 and 100\"<\/span>;\n                <span class=\"has-inline-color has-vivid-cyan-blue-color\">assertTrue<\/span>(theErrorMessage4, ((theResult &lt;= MAXRESULT)&amp;&amp;(theResult&gt;=MINRESULT)));\n        }\n\n\n    }\n}\n<\/code><\/pre>\n\n\n\n<p>I've made this unit tester a lot more verbose than it has to be.  To run the unit test, go into the file that you have defined the unit test class in and press the \"run\" icon:<\/p>\n\n\n\n<div class=\"wp-block-image\"><figure class=\"aligncenter size-large is-resized\"><img loading=\"lazy\" decoding=\"async\" src=\"https:\/\/www.yorku.ca\/professor\/drsmith\/wp-content\/uploads\/sites\/444\/2024\/03\/Screenshot-2024-03-25-at-5.56.19\u202fPM-1024x434.png\" alt=\"running a unit test.  Steps 1 and 2 shown.\" class=\"wp-image-3372\" width=\"768\" height=\"326\" srcset=\"https:\/\/www.yorku.ca\/professor\/drsmith\/wp-content\/uploads\/sites\/444\/2024\/03\/Screenshot-2024-03-25-at-5.56.19\u202fPM-1024x434.png 1024w, https:\/\/www.yorku.ca\/professor\/drsmith\/wp-content\/uploads\/sites\/444\/2024\/03\/Screenshot-2024-03-25-at-5.56.19\u202fPM-300x127.png 300w, https:\/\/www.yorku.ca\/professor\/drsmith\/wp-content\/uploads\/sites\/444\/2024\/03\/Screenshot-2024-03-25-at-5.56.19\u202fPM-1536x651.png 1536w, https:\/\/www.yorku.ca\/professor\/drsmith\/wp-content\/uploads\/sites\/444\/2024\/03\/Screenshot-2024-03-25-at-5.56.19\u202fPM-2048x869.png 2048w\" sizes=\"auto, (max-width: 768px) 100vw, 768px\" \/><figcaption>Running a unit test. Steps 1 and 2 shown.<\/figcaption><\/figure><\/div>\n\n\n\n\n\n\n\n<hr class=\"wp-block-separator\"\/>\n\n\n\n<div class=\"wp-block-image\"><figure class=\"alignleft size-full\"><img loading=\"lazy\" decoding=\"async\" width=\"128\" height=\"128\" src=\"https:\/\/www.yorku.ca\/professor\/drsmith\/wp-content\/uploads\/sites\/444\/2021\/12\/noun-signature-1720818-2.png\" alt=\"a pen\" class=\"wp-image-2116\"\/><\/figure><\/div>\n\n\n\n<p>James Andrew Smith is a Professional Engineer and Associate Professor in the Electrical Engineering and Computer Science\u00a0<a href=\"http:\/\/eecs.lassonde.yorku.ca\">Department<\/a>\u00a0of York University's\u00a0<a href=\"http:\/\/lassonde.yorku.ca\">Lassonde School<\/a>, with degrees in Electrical and Mechanical Engineering\u00a0from the University of Alberta and McGill University.\u00a0\u00a0Previously a program director in biomedical engineering, his research background spans robotics, locomotion, human birth and\u00a0engineering\u00a0education. While on sabbatical in 2018-19 with his wife and kids he lived in Strasbourg, France and\u00a0he\u00a0taught at the\u00a0<a href=\"https:\/\/www.insa-strasbourg.fr\/en\/\">INSA Strasbourg<\/a>\u00a0and\u00a0<a href=\"https:\/\/www.hs-karlsruhe.de\">Hochschule Karlsruhe<\/a>\u00a0and wrote about his\u00a0<a href=\"https:\/\/twitter.com\/search?q=(%23sabbaticallife)%20(from%3Aonnimikki)&amp;src=typed_query\">personal<\/a>\u00a0and\u00a0<a href=\"https:\/\/twitter.com\/search?q=insa%20(from%3Ajasmith_yorku)&amp;src=typed_query\">professional\u00a0<\/a><a href=\"https:\/\/twitter.com\/search?q=karlsruhe%20(from%3Ajasmith_yorku)&amp;src=typed_query\">perspectives<\/a>.\u00a0\u00a0James is a proponent of using social media to advocate for justice, equity, diversity and inclusion as well as evidence-based applications of research\u00a0in the public sphere.\u00a0You can find him on\u00a0<a href=\"https:\/\/twitter.com\/jasmith_yorku\">Twitter<\/a>. Originally from Qu\u00e9bec City, he now lives in Toronto, Canada.\u00a0\u00a0<\/p>\n","protected":false},"excerpt":{"rendered":"<p>It's important to create test frameworks for your programs. In Java we use the jUnit system to do so. Here is an example of setting up a unit tester to make sure that that a method returns the values it's supposed to. First, let's look at the method. I'm using it to convert values that [&hellip;]<\/p>\n","protected":false},"author":762,"featured_media":0,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"_kad_blocks_custom_css":"","_kad_blocks_head_custom_js":"","_kad_blocks_body_custom_js":"","_kad_blocks_footer_custom_js":"","footnotes":""},"categories":[50],"tags":[671,480],"class_list":["post-3370","post","type-post","status-publish","format-standard","hentry","category-java","tag-junit","tag-unit-test"],"taxonomy_info":{"category":[{"value":50,"label":"java"}],"post_tag":[{"value":671,"label":"junit"},{"value":480,"label":"unit test"}]},"featured_image_src_large":false,"author_info":{"display_name":"drsmith","author_link":"https:\/\/www.yorku.ca\/professor\/drsmith\/author\/drsmith\/"},"comment_info":"","category_info":[{"term_id":50,"name":"java","slug":"java","term_group":0,"term_taxonomy_id":50,"taxonomy":"category","description":"","parent":0,"count":27,"filter":"raw","cat_ID":50,"category_count":27,"category_description":"","cat_name":"java","category_nicename":"java","category_parent":0}],"tag_info":[{"term_id":671,"name":"junit","slug":"junit","term_group":0,"term_taxonomy_id":671,"taxonomy":"post_tag","description":"","parent":0,"count":1,"filter":"raw"},{"term_id":480,"name":"unit test","slug":"unit-test","term_group":0,"term_taxonomy_id":480,"taxonomy":"post_tag","description":"","parent":0,"count":6,"filter":"raw"}],"_links":{"self":[{"href":"https:\/\/www.yorku.ca\/professor\/drsmith\/wp-json\/wp\/v2\/posts\/3370","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.yorku.ca\/professor\/drsmith\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.yorku.ca\/professor\/drsmith\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.yorku.ca\/professor\/drsmith\/wp-json\/wp\/v2\/users\/762"}],"replies":[{"embeddable":true,"href":"https:\/\/www.yorku.ca\/professor\/drsmith\/wp-json\/wp\/v2\/comments?post=3370"}],"version-history":[{"count":2,"href":"https:\/\/www.yorku.ca\/professor\/drsmith\/wp-json\/wp\/v2\/posts\/3370\/revisions"}],"predecessor-version":[{"id":3373,"href":"https:\/\/www.yorku.ca\/professor\/drsmith\/wp-json\/wp\/v2\/posts\/3370\/revisions\/3373"}],"wp:attachment":[{"href":"https:\/\/www.yorku.ca\/professor\/drsmith\/wp-json\/wp\/v2\/media?parent=3370"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.yorku.ca\/professor\/drsmith\/wp-json\/wp\/v2\/categories?post=3370"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.yorku.ca\/professor\/drsmith\/wp-json\/wp\/v2\/tags?post=3370"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}