White Box Testing
Test your code
   Home      UnitTestingWithJUnit4
 
This is a brief tutorial on JUnit 4. The goal is to introduce the basics of JUnit 4 framework.
 
Install JUnit 4, JDK 5 and Eclipse IDE to create and run Java programs
 
Divide your testing in Test method, Test classes and Test suite. And write test framework in bottom up approach.
 
Unit test framework must have some support to take fragment of code as whole test. JUnit supports registering method as tests and treat that method as test.
 
Write test method for each method for every class file to be tested. Method name must begin with annotation @Test and you don’t need to prefix your test cases with “test”. Annotation @Test identifies that this method is a test method. Following are the test annotation to write test method.
 
@Test Annotation @Test identifies that this method is a test method.
 
          @Test
            public final void testAdd() {
                        Calculator cal = new Calculator();
                        long result = cal.add(3, 4);
                        assertEquals("actual not matching with expected", result, 7);
            }
 
@Test(expected=IllegalArgumentException.class) Tests if the method throws the named exception and fails if the different exception thrown or test method does not throw an exception.
 
            @Test(expected = ArithmeticException.class)
            public void exceptionTest() {
                        Calculator cal = new Calculator();
                        cal.divide(1, 0);
            }
 
@Test(timeout=100) Fails if the method takes longer than specified timeout 100 milliseconds.
 
            @Test(timeout=50)
            public final void testAdd() {
                        Calculator cal = new Calculator();
                        long result = cal.add(3, 4);
                        assertEquals("actual not matching with expected", result, 7);
            }
 
Use annotation @Ignore if code changed and test are not ready to run this time. Optionally you can add string parameter that defines the reason to ignore the test case.
 
            @Ignore(not ready to run)
            @Test
            public final void testRational() {
                        Calculator cal = new Calculator();
                        long result = cal.rational(10, 4);
                        assertEquals("actual not matching with expected", result, 2);
            }
 
Write test classes for every class to be tested.
 
An import statement to bring in junit.framework. import package org.junit.Test to bring junit methods required for test classes and org.junit.Assert to bring assert methods.
 
test class does not need to extend from “TestCase” class.
A typical test class comprises of following components
Test class fixture setup starting with annotation @BeforeClass.
Test method fixture setup starting with annotation @Before.
Unit tests starting with annotation @Test
Test method fixture teardown starting with annotation @After.
Test class fixture teardown starting with annotation @AfterClass.
 
All the unit tests of a test class share the fixture code. In order to run each test independently, fixture setup starting with annotation @Before will be called before each one of the testmethod get executed, and the fixture teardown starting with annotation @After will be called after each test method get executed.
 
In order to share fixture code class wide use annotation  @BeforeClass and @AfterClass.fixture setup starting with annotation @BeforeClass will be called before all the test method of the class get executed , and the fixture teardown starting with annotation @AfterClass will be called after all the test method of the class get executed. Test class setup and teardown will be called one time before and after all the test cases.
 
To run tests from the command line, run
java org.junit.runner.JUnitCore TestClass1 TestClass2 ...
 
For one-shot test runs
org.junit.runner.JUnitCore.runClasses(TestClass1.class, ...)
 
import static org.junit.Assert.*;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
public class CalculatorTest {
 
            @BeforeClass
            public static void setUpBeforeClass() throws Exception {
            }
 
            @AfterClass
            public static void tearDownAfterClass() throws Exception {
            }
 
            @Before
            public void setUp() throws Exception {
            }
 
            @After
            public void tearDown() throws Exception {
            }
 
            @Test
            public final void testAdd() {
                        Calculator cal = new Calculator();
                        long result = cal.add(3, 4);
                        assertEquals("actual not matching with expected", result, 7);
            }
 
            @Test
            public final void testSubtract() {
                        Calculator cal = new Calculator();
                        long result = cal.subtract(10, 5);
                        assertEquals("actual not matching with expected", result, 5);
            }
 
            @Test
            public final void testMultiply() {
                        Calculator cal = new Calculator();
                        long result = cal.multiply(10, 5);
                        assertEquals("actual not matching with expected", result, 50);
            }
 
            @Test
            public final void testDivide() {
                        Calculator cal = new Calculator();
                        long result = cal.divide(10, 5);
                        assertEquals("actual not matching with expected", result, 2);
            }
 
            @Test(expected = ArithmeticException.class)
            public void exceptionTest() {
                        Calculator cal = new Calculator();
                        cal.divide(1, 0);
            }
}
 
 
Using Suite as runner allows you to make suite of multiple test classes. To make test suite, annotate a class with @RunWith(Suite.class) and @SuiteClasses( {TestClass1.class, ...})
 
An import statement to bring in junit runner and suite
 
import org.junit.runner.RunWith;
import org.junit.runners.Suite;
 
@RunWith(Suite.class)
@Suite.SuiteClasses({
  CalculatorTest.class
 
 
})
 
public class CalcSuite {
    // the class remains empty,
}
 
It is a test suite launcher. Test runner extends abstract base class Runner. User can write own test runner extending Runner.
 
Test runner saves the outcomes of executing a Test Case in Result. Result keeps track of all the passes and failures/errors of test method.
 
Test listener useful while creating reports from Result. Runners implement RunListener to create useful report from the Result. User needs to interact with RunListener If they are implementing some other mechanism for test result reports.
To determine whether a method under test is performing correctly or not we use assertions. They tell you that some condition is true, equal, or not, and so on.
 
assertArrayEquals: Assert that two arrays are equal
assertArrayEquals(String message, expecteds, actuals)
message: An optional field that will be reported in the event of a failure or error.
expecteds: array value that is to be expected after running test
actuals: array value actually produced by the code under test
 
assertEquals:Assert two objects or primitive data type equal
assertEquals(String message, expected, actual)
assertEquals(String message, expected, actual, tolerance)
message: An optional field that will be reported in the event of a failure or error.
expected: value that is to be expected after running test
actual: value actually produced by the code under test
tolerance: An optional field that discard decimal digit for floating point numbers
 
assertNull:Assert that an object is null
assertNull(String message, java.lang.Object object)
assertNotNull:Assert that an object is not null
assertNotNull(String message, java.lang.Object object)
message: An optional field that will be reported in the event of a failure or error.
object: To test that the given object is null (or not null).
 
assertSame:Assert two object refer to same object
assertSame(String message, expected, actual)
assertNotSame:Assert two object do not refer to same object
assertNotSame(String message, expected, actual)
message: An optional field that will be reported in the event of a failure or error.
expected: the object that is expected to be same or not with actual object after running test
actual: the object actually produced by the code under test
 
assertTrue:Assert the condition is true
assertTrue(String message, boolean condition)
assertFalse:Assert the condition is false
assertFalse(String message, boolean condition)
message: An optional field that will be reported in the event of a failure or error.
condition:The conditional statement tested to be true or false
 
Fail:This method should be called for unexpected error
fail(String message)
 
message: An optional field that will be reported in the event of a failure or error.