JUnit

From CS315

Jump to: navigation, search

JUnit is a unit testing framework available for the Java programming language. It is used for its ease in performing numerous test cases against Java code.


Contents

How to Use JUnit

Downloading

Download the JUnit install file from the main JUnit website (the latest version is 4.4) and add the JUnit jar file to your project's classpath.

TestCase

To write a test case import JUnit.framework.Assert and JUnit.framework.Testcase into the class which contains the tests. You must also import junit.texttui.TestRunner and junit.framework.TestSuite into the class whose main method will be run. In the class which extends TestCase class Assert methods can be added to test for program correctness.

Assert Methods

  • assertTrue() and assertFalse()
    • test passes if the expression passed as the parameter is true or false, respectively.
  • assertEquals()
    • test passes if the two parameters passed in are equivalent
  • assertNotNull() and assertNull()
    • test passes if the object passed as a paramter is not/is pointing to null
  • assertSame() and assertNotSame()
    • test passes if the object or string parameters passed in are equivalent

Examples

The following is an example of a JUnit test case from Project 2:

   public class DecipherTest extends TestCase {
       public void testRotate () {
           {
           StringBuilder s = new StringBuilder("abc");
           Decipher.rotate(s, 1);
           Assert.assertEquals(s.toString(), "abc");
           }}}


TestSuite

To write a testsuite, create a Java class that defines a static suite() factory method that creates a TestSuite containing all tests. One can also optionally define a main() method that runs the TestSuite in batch mode.

Running

Simply run either the testCase() or testSuite() you wish to test. JUnit will respond with the total time it took to complete the test along with the number passes, failed, tests in error, along with information about where the code failed.

Example of a JUnit RunTest

The following is an example of a JUnit test case from Project 2:

.....F.....
Time: 0
There was 1 failure:          
1) testVertices(cs.projects.graph.TestGraph)junit.framework.AssertionFailedError: expected:<3> but was <2>      
at cs.projects.graph.TestGraph.testVertices(TestGraph.java:49)          
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at Application.main(Application.java:31)      	
       
FAILURES!!!       	
Tests run: 10,  Failures: 1,  Errors: 0
          
Done.

Links

Written by Danny Thomas

Personal tools