ArtsAutosBooksBusinessEducationEntertainmentFamilyFashionFoodGamesGenderHealthHolidaysHomeHubPagesPersonal FinancePetsPoliticsReligionSportsTechnologyTravel

Common and Basic JUnit Unit Testing Annotation: InterInterview Questions & Answers, examples, notes and explanation

Updated on January 2, 2014

What is required for unit testing in JUnit?

We need to write / create Test method using @Test in JUnit to create unit testing.

What is JUnit Test methods?

JUnit Test methods are the methods which are created for unit testing in JUnit.

@Test
@Before
@After
@BeforeClass
@AfterClass
@Ignore
@Test(timeout = 10)
@Test(expected = Exception.class)

What is the use of @Test?

The @Test annotation identifies a method as a test method. To create any test method, we must have to use this before the method definition.

In a test class, there are 100 test cases. You want not to execute two test case. How do you do this?

We have to use @Ignore annotation before the test cases which we do not want to execute.

What is the differences between @Before and @BeforeClass

@Before test case is executed before each execution but @BeforeClass test case is executed only before the test class starts.

In an environment, we have 10 test cases. But each time we need to create the object. Do we need to create object explicitly each time into the test cases?

No. We do not need to create object for each test case. We can use @Before annotation so that it can create object each time it needs the object.

In an production environment, we need to test whether a method execute less then 100milliseconds, How do you test this?

We can use the timeout and define the timeout value. So, that we could easily figure out whether the method is executed withing the defined time or not.

Why it is good to use exception in test cases?

Exception annotation in test case fails only when the method does not throw the named exception. So, we can easily check the method.

Before creating test cases, we need to see the methods to which we would test. Suppose, we have a class CalculationMethodods.java which has some methods like addition, subtraction, multiplication etc. The project structure and methods definition are the following:

package com.hubpages.plusminus;

public class CalculationMethods {

	public int addition(String x1, String x2) {

		int a1 = Integer.parseInt(x1);
		int a2 = Integer.parseInt(x2);
		int result = 0;

		result = a1 + a2;

		return result;
	}

	public int subtraction(String x1, String x2) {

		int a1 = Integer.parseInt(x1);
		int a2 = Integer.parseInt(x2);
		int result = 0;

		result = a1 - a2;

		return result;
	}

	public int multiplication(String x1, String x2) {

		int a1 = Integer.parseInt(x1);
		int a2 = Integer.parseInt(x2);
		int result = 0;

		result = a1 * a2;

		return result;
	}

	public int division(String x1, String x2) {

		float a1 = Float.parseFloat(x1);
		float a2 = Float.parseFloat(x2);

		int result = 0;

		result = (int) (a1 / a2);

		return result;
	}
}

Now, we will write some test case which can test all the methods of the above code blocks. The test cases are the following:

package com.hubpages.plusminus;

import org.junit.Test;
import static org.junit.Assert.*;

public class CalculationMethodsTest {

	@Test
	public void additionMethodTest50Add50() {
		CalculationMethods method = new CalculationMethods();
		assertEquals("Sum of 50 and 50 is not 100", 100,
				method.addition("50", "50"));
	}

	@Test
	public void multiplicationMethodTest10Multiply20() {
		CalculationMethods method = new CalculationMethods();
		assertEquals("Multiplication of 10 & 20 is not 200", 200,
				method.multiplication("10", "20"));
	}

	@Test
	public void subtractionMethodTestForValues50Subtact20() {
		CalculationMethods method = new CalculationMethods();
		assertEquals("Subtraction from 50 to 20 is not 30", 30,
				method.subtraction("50", "20"));
	}

	@Test
	public void subtractionMethodTestForValues10DivideBy5() {
		CalculationMethods method = new CalculationMethods();
		assertEquals("Divide 10 by 5 is not 2", 2, method.division("10", "5"));
	}

}

We run the program in JUnit and it shows the following output:

See the above test cases, we define the same object multiple times. This is a repetitive task. In the following figure you will see the repetition of those object creation.

Our target is to eliminate the repetition. And we can do so by using @Before annotation. In the flowing we remove the repetitive codes and create a new block using @Before annotation.

package com.hubpages.plusminus;

import org.junit.Before;
import org.junit.Test;

import static org.junit.Assert.*;

public class CalculationMethodsTest {

	private CalculationMethods method;

	@Before
	public void setup() {
		method = new CalculationMethods();
		System.out.println("Before test");
	}

	@Test
	public void additionMethodTest50Add50() {
		assertEquals("Sum of 50 and 50 is not 100", 100,
				method.addition("50", "50"));
	}

	@Test
	public void multiplicationMethodTest10Multiply20() {
		assertEquals("Multiplication of 10 & 20 is not 200", 200,
				method.multiplication("10", "20"));
	}

	@Test
	public void subtractionMethodTestForValues50Subtact20() {
		assertEquals("Subtraction from 50 to 20 is not 30", 30,
				method.subtraction("50", "20"));
	}

	@Test
	public void subtractionMethodTestForValues10DivideBy5() {
		assertEquals("Divide 10 by 5 is not 2", 2, method.division("10", "5"));
	}

}
package com.hubpages.plusminus;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import static org.junit.Assert.*;

public class CalculationMethodsTest {

	private CalculationMethods method;

	@Before
	public void setup() {
		method = new CalculationMethods();
		System.out.println("Before test");
	}

	@After
	public void end() {
		System.out.println("After test case");
	}

	@Test
	public void additionMethodTest50Add50() {
		assertEquals("Sum of 50 and 50 is not 100", 100,
				method.addition("50", "50"));
	}

	@Test
	public void multiplicationMethodTest10Multiply20() {
		assertEquals("Multiplication of 10 & 20 is not 200", 200,
				method.multiplication("10", "20"));
	}

	@Test
	public void subtractionMethodTestForValues50Subtact20() {
		assertEquals("Subtraction from 50 to 20 is not 30", 30,
				method.subtraction("50", "20"));
	}

	@Test
	public void subtractionMethodTestForValues10DivideBy5() {
		assertEquals("Divide 10 by 5 is not 2", 2, method.division("10", "5"));
	}

}

JUnit testing using BeforeClass And AferClass

package com.hubpages.plusminus;

import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;

import static org.junit.Assert.*;

public class CalculationMethodsTest {

	private CalculationMethods method;

	@Before
	public void setup() {
		method = new CalculationMethods();
		System.out.println("Before");
	}

	@After
	public void end() {
		System.out.println("After");
	}

	@BeforeClass
	public static void beforeClassDemo() {
		System.out.println("Before class");
	}

	@AfterClass
	public static void afterClassDemo() {
		System.out.println("After class");
	}

	@Test
	public void additionMethodTest50Add50() {
		assertEquals("Sum of 50 and 50 is not 100", 100,
				method.addition("50", "50"));
	}

	@Test
	public void multiplicationMethodTest10Multiply20() {
		assertEquals("Multiplication of 10 & 20 is not 200", 200,
				method.multiplication("10", "20"));
	}

	@Test
	public void subtractionMethodTestForValues50Subtact20() {
		assertEquals("Subtraction from 50 to 20 is not 30", 30,
				method.subtraction("50", "20"));
	}

	@Test
	public void subtractionMethodTestForValues10DivideBy5() {
		assertEquals("Divide 10 by 5 is not 2", 2, method.division("10", "5"));
	}

}

JUnit testing: Using Timeout

In this example, we will use timeout to test whether the test case is completed successfully with a defined time value. To do this, we create a method counter into CalculationMethods class and add a filed finalValue. So, we need to add the following line of codes into the CalculationMethods class.

        private long finalValue = 0;

	public long counter(long x) {

		finalValue = finalValue + x;

		return finalValue;

	}

Our goal is to check whether the method can do a repetitive task by a defined time frame. So, we will add a method badTest which will try to call the method counter repeatedly. And we will check whether this can completed within 100 milliseconds The code for this function is the following:

	@Test(timeout=10)
	public void badTest(){
		for (int i = 0; i < 50000000; i++) {
			
			method.counter(i);
			
		}
		
	}

Now, let's try to run the test case. When the JUnit runner finishes the test, we will see that the test failed. JUnit output may look like the following:

The full codes of this are the following:

Full code of CalculationMethods.java

package com.hubpages.plusminus;

public class CalculationMethods {

	private long finalValue = 0;

	public int addition(String x1, String x2) {

		int a1 = Integer.parseInt(x1);
		int a2 = Integer.parseInt(x2);
		int result = 0;

		result = a1 + a2;

		return result;
	}

	public int subtraction(String x1, String x2) {

		int a1 = Integer.parseInt(x1);
		int a2 = Integer.parseInt(x2);
		int result = 0;

		result = a1 - a2;

		return result;
	}

	public int multiplication(String x1, String x2) {

		int a1 = Integer.parseInt(x1);
		int a2 = Integer.parseInt(x2);
		int result = 0;

		result = a1 * a2;

		return result;
	}

	public int division(String x1, String x2) {

		float a1 = Float.parseFloat(x1);
		float a2 = Float.parseFloat(x2);

		int result = 0;

		result = (int) (a1 / a2);

		return result;
	}

	public long counter(long x) {

		finalValue = finalValue + x;

		return finalValue;

	}
}

Full code of CalculationMethodsTest.java

package com.hubpages.plusminus;

import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;

import static org.junit.Assert.*;

public class CalculationMethodsTest {

	private CalculationMethods method;

	@Before
	public void setup() {
		method = new CalculationMethods();
		System.out.println("Before");
	}

	@After
	public void end() {
		System.out.println("After");
	}

	@BeforeClass
	public static void beforeClassDemo() {
		System.out.println("Before class");
	}

	@AfterClass
	public static void afterClassDemo() {
		System.out.println("After class");
	}

	@Test
	public void additionMethodTest50Add50() {
		assertEquals("Sum of 50 and 50 is not 100", 100,
				method.addition("50", "50"));
	}

	@Test
	public void multiplicationMethodTest10Multiply20() {
		assertEquals("Multiplication of 10 & 20 is not 200", 200,
				method.multiplication("10", "20"));
	}

	@Test
	public void subtractionMethodTestForValues50Subtact20() {
		assertEquals("Subtraction from 50 to 20 is not 30", 30,
				method.subtraction("50", "20"));
	}

	@Test
	public void subtractionMethodTestForValues10DivideBy5() {
		assertEquals("Divide 10 by 5 is not 2", 2, method.division("10", "5"));
	}
	
	@Test(timeout=10)
	public void badTest(){
		for (int i = 0; i < 50000000; i++) {
			
			method.counter(i);
			
		}
		
	}

}

JUnit test using Ignore

Sometimes, we may need to ignore some test case during testing. But we don't need to delete the test case. We can use @Ignore to do this.

        @Test(timeout=10)
	@Ignore
	public void badTest(){
		for (int i = 0; i < 50000000; i++) {
			
			method.counter(i);
			System.out.println("value of i" + i);
			
		}
	private int goalValue = 0;
	public int settingGoalValue(int passedValue) throws InvalidCounterException {

		goalValue += passedValue;

		if (goalValue > 50) {
			throw new InvalidCounterException();
		}
		return goalValue;

	}
package com.hubpages.plusminus;

public class InvalidCounterException extends Exception {

	private static final long serialVersionUID = 1L;

}
        @Test(expected = InvalidCounterException.class)
	public void whenGoalValueIsGereaterThan50ExceptionIsThrown()
			throws InvalidCounterException {
		method.settingGoalValue(200);
	}

Summary of all codes

In this tutorial, we write test cases and test those test cases. We use tests using Before, using After, using BeforeClass, using AfterClass, using Timing, using Ignore and using Exception testing. All these test cases are really helpful to test the java codes. The full codes of this tutorial and the structure of this tutorial are the followings:

Projects structure

Projects structure [more details]

Full code of CalculationMethods.java

package com.hubpages.plusminus;

public class CalculationMethods {

	private long finalValue = 0;
	private int goalValue = 0;

	public int addition(String x1, String x2) {

		int a1 = Integer.parseInt(x1);
		int a2 = Integer.parseInt(x2);
		int result = 0;

		result = a1 + a2;

		return result;
	}

	public int subtraction(String x1, String x2) {

		int a1 = Integer.parseInt(x1);
		int a2 = Integer.parseInt(x2);
		int result = 0;

		result = a1 - a2;

		return result;
	}

	public int multiplication(String x1, String x2) {

		int a1 = Integer.parseInt(x1);
		int a2 = Integer.parseInt(x2);
		int result = 0;

		result = a1 * a2;

		return result;
	}

	public int division(String x1, String x2) {

		float a1 = Float.parseFloat(x1);
		float a2 = Float.parseFloat(x2);

		int result = 0;

		result = (int) (a1 / a2);

		return result;
	}

	public long counter(long x) {

		finalValue = finalValue + x;
		return finalValue;

	}

	public int settingGoalValue(int passedValue) throws InvalidCounterException {

		goalValue += passedValue;

		if (goalValue > 50) {
			throw new InvalidCounterException();
		}
		return goalValue;

	}
}

Full code of CalculationMethodsTest.java

package com.hubpages.plusminus;

import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Ignore;
import org.junit.Test;

import static org.junit.Assert.*;

public class CalculationMethodsTest {

	private CalculationMethods method;

	@Before
	public void setup() {
		method = new CalculationMethods();
		System.out.println("Before");
	}

	@After
	public void end() {
		System.out.println("After");
	}

	@BeforeClass
	public static void beforeClassDemo() {
		System.out.println("Before class");
	}

	@AfterClass
	public static void afterClassDemo() {
		System.out.println("After class");
	}

	@Test
	public void additionMethodTest50Add50() {
		assertEquals("Sum of 50 and 50 is not 100", 100,
				method.addition("50", "50"));
	}

	@Test
	public void multiplicationMethodTest10Multiply20() {
		assertEquals("Multiplication of 10 & 20 is not 200", 200,
				method.multiplication("10", "20"));
	}

	@Test
	public void subtractionMethodTestForValues50Subtact20() {
		assertEquals("Subtraction from 50 to 20 is not 30", 30,
				method.subtraction("50", "20"));
	}

	@Test
	public void subtractionMethodTestForValues10DivideBy5() {
		assertEquals("Divide 10 by 5 is not 2", 2, method.division("10", "5"));
	}

	@Test(timeout = 10)
	@Ignore
	public void badTest() {
		for (int i = 0; i < 50000000; i++) {

			method.counter(i);
			System.out.println("value of i" + i);

		}

	}

	@Test(expected = InvalidCounterException.class)
	public void whenGoalValueIsGereaterThan50ExceptionIsThrown()
			throws InvalidCounterException {
		method.settingGoalValue(200);
	}

}

Summary of Annotations

(click column header to sort results)
Annotation  
Description  
@Test public void methodName(){ }
identifies a method as a test method
@Test (expected = Exception.class) public void methodName(){ }
fails, if the method does not throw the named exception
@Test(timeout=10) public void methodName(){ }
fails, if the method takes longer than 10 milliseconds
@Ignore public void methodName(){ }
ignores the test method. This is useful when the underlying code has been changed and the test case has not yet been adapted. Or if the execution time of this test is too long to be included.
@Before public void methodName(){ }
method is executed before each test. It is used to can prepare the test environment (e.g. read input data, initialize the class)
@After public void methodName(){ }
ethod is executed after each test. It is used to cleanup the test environment (e.g. delete temporary data, restore defaults). It can also save memory by cleaning up expensive memory structures
@BeforeClass public void methodName(){ }
method is executed once, before the start of all tests. It is used to perform time intensive activities, for example to connect to a database. Methods annotated with this annotation need to be defined as static to work with JUnit
@AfterClass public void methodName(){ }
method is executed once, after all tests have been finished. It is used to perform clean-up activities, for example to disconnect from a database. Methods annotated with this annotation need to be defined as static to work with JUnit

Comments

    0 of 8192 characters used
    Post Comment

    No comments yet.

    Click to Rate This Article