Note that there are some explanatory texts on larger screens.

plurals
  1. POJUnit for Functions with Void Return Values
    text
    copied!<p>I've been working on a Java application where I have to use JUnit for testing. I am learning it as I go. So far I find it to be useful, especially when used in conjunction with the Eclipse JUnit plugin.</p> <p>After playing around a bit, I developed a consistent method for building my unit tests for functions with no return values. I wanted to share it here and ask others to comment. Do you have any suggested improvements or alternative ways to accomplish the same goal?</p> <p><strong>Common Return Values</strong></p> <p>First, there's an enumeration which is used to store values representing test outcomes.</p> <pre><code>public enum UnitTestReturnValues { noException, unexpectedException // etc... } </code></pre> <p><strong>Generalized Test</strong></p> <p>Let's say a unit test is being written for:</p> <pre><code>public class SomeClass { public void targetFunction (int x, int y) { // ... } } </code></pre> <p>The JUnit test class would be created:</p> <pre><code>import junit.framework.TestCase; public class TestSomeClass extends TestCase { // ... } </code></pre> <p>Within this class, I create a function which is used for every call to the target function being tested. It catches all exceptions and returns a message based on the outcome. For example:</p> <pre><code>public class TestSomeClass extends TestCase { private UnitTestReturnValues callTargetFunction (int x, int y) { UnitTestReturnValues outcome = UnitTestReturnValues.noException; SomeClass testObj = new SomeClass (); try { testObj.targetFunction (x, y); } catch (Exception e) { UnitTestReturnValues.unexpectedException; } return outcome; } } </code></pre> <p><strong>JUnit Tests</strong></p> <p>Functions called by JUnit begin with a lowercase "test" in the function name, and they fail at the first failed assertion. To run multiple tests on the targetFunction above, it would be written as:</p> <pre><code>public class TestSomeClass extends TestCase { public void testTargetFunctionNegatives () { assertEquals ( callTargetFunction (-1, -1), UnitTestReturnValues.noException); } public void testTargetFunctionZeros () { assertEquals ( callTargetFunction (0, 0), UnitTestReturnValues.noException); } // and so on... } </code></pre> <p>Please let me know if you have any suggestions or improvements. Keep in mind that I am in the process of learning how to use JUnit, so I'm sure there are existing tools available that might make this process easier. Thanks!</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload