JUnit is used for unit testing of Java applications. JUnit and TestNG are two popular unit testing frameworks. In this tutorial I will explore JUnit only.

There are two popular version of JUnit – JUnit 3 and JUnit 4. Below table shows few important differences in these versions . Apart from this there is one more important difference that from JUnit 4.7 parallel execution of JUnit test cases is supported.

JUnit3-Junit4

 

JUnit 3.x Sample

import junit.framework.*;
public class MoneyTest extends TestCase {
	private Money f12CHF;			// fixtures
	private Money f14CHF;

	protected void setUp() {		// create the test data
		f12CHF = new Money(12, "CHF");
		f14CHF = new Money(14, "CHF");
	}
   void testAdd() {				// create the test data
		Money expected = new Money(26, “CHF”);
		assertEquals(“amount not equal”,
                     expected,f12CHF.add(f14CHF);
	}
	...
}

JUnit 4.x Sample

import junit.framework.*;
import org.junit.*;
import static org.junit.Assert.*;
public class MoneyTest <del>extends TestCase</del> {
	private Money f12CHF;
	private Money f14CHF;

	@Before
        public void setUp() // setup, teardown function names are not mandatory now as we have annotations now
        {
		f12CHF = new Money(12, "CHF");    // - the fixture
		f14CHF = new Money(14, "CHF");
	}
	@Test
        public void testAdd() // create the test data
        {
		Money expected = new Money(26, “CHF”);
		assertEquals(“amount not equal”,
                     expected,f12CHF.add(f14CHF));
	}
	...
}

Following changes were happened in JUnit 4.x

  1. No need to start test method name with prefix “test”.
  2. @BeforeClass and @AfterClass were introduced
    1. @BeforeClass method – executes only once; before the first test method
    2. @AfterClass method – executes only once; after the last test method
  3. Instead of setup and tearDown now JUnit 4 has @Before and @After annotations.
    1. @Before method – executes every time; before the test method.
    2. @After method – executes every time; after the test method.
  4. @Ignore was introduced to skip a test case while running.
  5. “expected” was introduced to tell JUnitRunner that what exception we are expecting. Example : @Test(expected=ArithmeticException.class)
  6. “timeout” was introduced to put a time limit on a testcase. If test does not complete in that time limit, an exception will raise with message “test timed out after xxx milliseconds”

Next posts will show the working examples with these annotations.

Tagged on:

One thought on “JUnit Introduction

  • February 17, 2015 at 10:02 am
    Permalink

    Nice article Rahul.

    Reply

Leave a Reply to rajesh khore Cancel reply

Your email address will not be published.


You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>