JUnit

From CSWiki

Jump to: navigation, search

Contents

[edit] What is JUnit?

JUnit is a simple, open source framework to write and run repeatable tests.It is an instance of the xUnit architecture for unit testing frameworks.

[edit] Why is JUnit important?

The simplest way to test is as an expression in a debugger.You can change debug expressions without recompiling, and you can wait to decide what to write until you have seen the running objects. You can also write test expressions as statements which print to the standard output stream. Both styles of tests are limited because they require human judgment to analyze their results. Also, they don't compose nicely- you can only execute one debug expression at a time and a program with too many print statements causes the dreaded "Scroll Blindness.

[edit] What is the feature of JUnit?

JUnit features include:

Assertions for testing expected results

Test fixtures for sharing common test data

Test runners for running tests

JUnit tests do not require human judgment to interpret, and it is easy to run many of them at the same time. When you need to test something.

[edit] When we use JUnit?

Here are a couple of the times that you will receive a reasonable return on your testing investment:

During Development- When you need to add new functionality to the system, write the tests first. Then, you will be done developing when the test runs.


During Debugging- When someone discovers a defect in your code, first write a test that will succeed if the code is working. Then debug until the test succeeds.


[edit] How can we install JUnit?

First, download the latest version of JUnit, referred to below as junit.zip.

Then install JUnit on your platform of choice:

Windows

To install JUnit on Windows, follow these steps:

Unzip the junit.zip distribution file to a directory referred to as %JUNIT_HOME%.

Add JUnit to the classpath:

set CLASSPATH=%CLASSPATH%;%JUNIT_HOME%\junit.jar .

[edit] How do we write the test and run the test?

  1. Annotate a method with@org.junit.Test
  2. To check the value import org.junit.Assert.*and call assertTrue() and pass boolean that is true if the test success

sample1 code

sample2 code

[edit] What is the conclusion?

JUnit focuses on a style of testing that with a remarkably small investment will make you a faster, more productive, more predictable, and less stressed developer. Once you've been test infected, your attitude toward development is likely to change.

[edit] More

From the JUnit sourceforge page:

"JUnit is a simple framework to write repeatable tests. It is an instance of the xUnit architecture for unit testing frameworks."

My previous research topic (Apache Ant) made reference to JUnit interoperability, so I thought I'd explore this.

From the JUnit cookbook:

Simple Test Case

How do you write testing code?

The simplest way is as an expression in a debugger. You can change debug expressions without recompiling, and you can wait to decide what to write until you have seen the running objects. You can also write test expressions as statements which print to the standard output stream. Both styles of tests are limited because they require human judgment to analyze their results. Also, they don't compose nicely- you can only execute one debug expression at a time and a program with too many print statements causes the dreaded "Scroll Blindness".

JUnit tests do not require human judgment to interpret, and it is easy to run many of them at the same time. When you need to test something, here is what you do:

  1. Annotate a method with @org.junit.Test
  2. When you want to check a value, import org.junit.Assert.* statically, call assertTrue() and pass a boolean that is true if the test succeeds

For example, to test that the sum of two Moneys with the same currency contains a value which is the sum of the values of the two Moneys, write:

   @Test public void simpleAdd() {
       Money m12CHF= new Money(12, "CHF"); 
       Money m14CHF= new Money(14, "CHF"); 
       Money expected= new Money(26, "CHF"); 
       Money result= m12CHF.add(m14CHF); 
       assertTrue(expected.equals(result));
   }

Within JUnit, there are tests, and there are test fixtures (and then Test Suites, hierarchically).

From the FAQ: "A test fixture is useful if you have two or more tests for a common set of objects. Using a test fixture avoids duplicating the code necessary to initialize (and cleanup) the common objects."

Here I will walk through the simple example of testing to test if an ArrayList is empty:

import org.junit.*;
import static org.junit.Assert.*;
import java.util.*;
 
public class SampleTest {
 
    // using java 1.5, we use generics to enforce type on the collection
    private List<String> emptyList;
 
    /**
     * Sets up the test fixture. 
     * (Called before every test case method.)
     */
    @Before
    public void setUp() {
    	
    		
        	emptyList = new ArrayList<String>();
                // uncomment this to get the test to fail
        	// then it's not an emptyList...
        	//emptyList.add("boo");
    }
 
    /**
     * Tears down the test fixture. 
     * (Called after every test case method.)
     */
    @After
    public void tearDown() {
        emptyList = null;
    }
    
    /**
     * this instance of assertEquals expects String, int expected, int actual
     * though you can overload this method in over 20 ways
     * see doc at http://junit.sourceforge.net/javadoc/junit/framework/Assert.html
     * */
    
    @Test
    public void testSomeBehavior() {
        assertEquals("Empty list should have 0 elements", 0, emptyList.size());
    }
 
    // we're looking for the exception here
    @Test(expected=IndexOutOfBoundsException.class)
    public void testForException() {
        Object o = emptyList.get(0);
    }
 
    // only for console running
    public static void main(String args[]) {
      org.junit.runner.JUnitCore.main("SampleTest");
    }
 
 
}


Eclipse provides a wonderful interface to JUnit, and comes bundled with Eclipse 3.x.

so I asked, why use JUnit? I came across this primer for JUnit http://clarkware.com/articles/JUnitPrimer.html which has a list of reasons to use JUnit, as well as some nice examples. It also shows how to create a Test Suite that allows us to run a number of regression test cases at once.

Personal tools