JUnit Test case for Java Classes

Junit is a framework that can be used to perform unit test cases on the classes written. Junit-4.0 provides for an option for the Test cases to be used along with the class by including the annotation @Test which tells the framework to run it as a test case.

Tests are run using assertions on whether the actual and expected output matches or not. Below is a sample program (JUnitSample.java) which has two methods add and divide, both taking two integer arguments and return integer result. This program also includes a test method addTest which asserts on the method add ( test case used within the class itself). The other class is the JUnit test case class (JunitSampleTest.java) which is the junit class for the former.

JunitSample.java –


package sample;

import static org.junit.Assert.assertEquals;

import org.junit.Test;

public class JunitSample {

	public JunitSample(){
		
	}
	
	public int add(int a , int b){
		return(a+b);
	}
	
	public int divide(int a , int b){
		try{
			/**
			 * if b is zero there is divide by zero exception and the method returns
			 * the value of a itself
			 */
			a = a/b;
		}
		catch(Exception e){
			e.printStackTrace();
		}
		return a;
	}
	/*
	 * JUnit test method which asserts on whether the method add is adding the two numbers
	 * 3 and 2 correctly or not
	 */
	@Test
	public void addTest(){
		assertEquals(5, new JunitSample().add(3, 2));
	}
	
	public static void main(String[] args) {
		new JunitSample();
	}

} 

JunitSampleTest.java –

package sample;

import static org.junit.Assert.*;

import org.junit.Test;

public class JunitSampleTest {
	
	@Test
	public void addTest(){
		assertEquals(5, new JunitSample().add(3, 2));
	}
	
	@Test
	public void divideTest(){
		assertEquals(1, new JunitSample().divide(3, 2));
	}
	
	@Test
	public void divideErrorTest(){
		/**
		 * This methods asserts that the method divide on passing 0 as second argument 
		 * returns the first argument as the method throws division by 0 exception as 
		 * defined by JUnitSample.divide()
		 */
		assertEquals(3,new JunitSample().divide(3, 0));
	}
	
}

Leave a comment