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.

    working

    This website uses cookies

    As a user in the EEA, your approval is needed on a few things. To provide a better website experience, hubpages.com uses cookies (and other similar technologies) and may collect, process, and share personal data. Please choose which areas of our service you consent to our doing so.

    For more information on managing or withdrawing consents and how we handle data, visit our Privacy Policy at: https://hubpages.com/privacy-policy#gdpr

    Show Details
    Necessary
    HubPages Device IDThis is used to identify particular browsers or devices when the access the service, and is used for security reasons.
    LoginThis is necessary to sign in to the HubPages Service.
    Google RecaptchaThis is used to prevent bots and spam. (Privacy Policy)
    AkismetThis is used to detect comment spam. (Privacy Policy)
    HubPages Google AnalyticsThis is used to provide data on traffic to our website, all personally identifyable data is anonymized. (Privacy Policy)
    HubPages Traffic PixelThis is used to collect data on traffic to articles and other pages on our site. Unless you are signed in to a HubPages account, all personally identifiable information is anonymized.
    Amazon Web ServicesThis is a cloud services platform that we used to host our service. (Privacy Policy)
    CloudflareThis is a cloud CDN service that we use to efficiently deliver files required for our service to operate such as javascript, cascading style sheets, images, and videos. (Privacy Policy)
    Google Hosted LibrariesJavascript software libraries such as jQuery are loaded at endpoints on the googleapis.com or gstatic.com domains, for performance and efficiency reasons. (Privacy Policy)
    Features
    Google Custom SearchThis is feature allows you to search the site. (Privacy Policy)
    Google MapsSome articles have Google Maps embedded in them. (Privacy Policy)
    Google ChartsThis is used to display charts and graphs on articles and the author center. (Privacy Policy)
    Google AdSense Host APIThis service allows you to sign up for or associate a Google AdSense account with HubPages, so that you can earn money from ads on your articles. No data is shared unless you engage with this feature. (Privacy Policy)
    Google YouTubeSome articles have YouTube videos embedded in them. (Privacy Policy)
    VimeoSome articles have Vimeo videos embedded in them. (Privacy Policy)
    PaypalThis is used for a registered author who enrolls in the HubPages Earnings program and requests to be paid via PayPal. No data is shared with Paypal unless you engage with this feature. (Privacy Policy)
    Facebook LoginYou can use this to streamline signing up for, or signing in to your Hubpages account. No data is shared with Facebook unless you engage with this feature. (Privacy Policy)
    MavenThis supports the Maven widget and search functionality. (Privacy Policy)
    Marketing
    Google AdSenseThis is an ad network. (Privacy Policy)
    Google DoubleClickGoogle provides ad serving technology and runs an ad network. (Privacy Policy)
    Index ExchangeThis is an ad network. (Privacy Policy)
    SovrnThis is an ad network. (Privacy Policy)
    Facebook AdsThis is an ad network. (Privacy Policy)
    Amazon Unified Ad MarketplaceThis is an ad network. (Privacy Policy)
    AppNexusThis is an ad network. (Privacy Policy)
    OpenxThis is an ad network. (Privacy Policy)
    Rubicon ProjectThis is an ad network. (Privacy Policy)
    TripleLiftThis is an ad network. (Privacy Policy)
    Say MediaWe partner with Say Media to deliver ad campaigns on our sites. (Privacy Policy)
    Remarketing PixelsWe may use remarketing pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to advertise the HubPages Service to people that have visited our sites.
    Conversion Tracking PixelsWe may use conversion tracking pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to identify when an advertisement has successfully resulted in the desired action, such as signing up for the HubPages Service or publishing an article on the HubPages Service.
    Statistics
    Author Google AnalyticsThis is used to provide traffic data and reports to the authors of articles on the HubPages Service. (Privacy Policy)
    ComscoreComScore is a media measurement and analytics company providing marketing data and analytics to enterprises, media and advertising agencies, and publishers. Non-consent will result in ComScore only processing obfuscated personal data. (Privacy Policy)
    Amazon Tracking PixelSome articles display amazon products as part of the Amazon Affiliate program, this pixel provides traffic statistics for those products (Privacy Policy)