Home » Core Java » junit » JUnit Time Test Example

About Konstantina Dimtsa

Konstantina Dimtsa
Konstantina has graduated from the Department of Informatics and Telecommunications in National and Kapodistrian University of Athens (NKUA) and she is currently pursuing M.Sc studies in Advanced Information Systems at the same department. She is also working as a research associate for NKUA in the field of telecommunications. Her main interests lie in software engineering, web applications, databases and telecommunications.

JUnit Time Test Example

In this example we are going to see how to use @Test annotation along with its optional parameter timeout in JUnit testing framework. Also, we will see how to run our test case from the command line by using the org.junit.runner.JUnitCore.

1. Create the java class to be tested

Create a folder named JUnitTest. This is the folder where your classes will be located. Using a text editor, create a Java class named FirstDayAtSchool.java. To make sure your file name is FirstDayAtSchool.java, (not FirstDayAtSchool.java.txt), first choose “Save as -> Save as type -> All files”, then type in the file name FirstDayAtSchool.java.

 
FirstDayAtSchool.java

public class FirstDayAtSchool {

	public String[] prepareMyBag() {
		String[] schoolbag = { "Books", "Notebooks", "Pens" };
		System.out.println("Preparing my bag");
		return (schoolbag);
	}

	public void printItems(String items) {
		System.out.println("My school bag contains: " + items);
		while (true);
	}
}

2. Create JUnit test case

In the same directory (JUnitTest), use a text editor and create a java class named JunitTest.java with the following code.

JunitTest.java

import static org.junit.Assert.assertArrayEquals;
import java.util.Arrays;
import org.junit.Test;

public class JunitTest {

   FirstDayAtSchool school = new FirstDayAtSchool();
   String[] bag = {"Books", "Notebooks", "Pens"};
  
   @Test
   public void testPrepareMyBag() {	
      System.out.println("Inside testPrepareMyBag()");    
      assertArrayEquals(bag, school.prepareMyBag());     
   }

   @Test(timeout=100)
   public void testPrintItems() {	 
      System.out.println("Inside printItems()");   
      school.printItems(Arrays.toString(bag)); 
   }
}

Inside the method testPrintItems(), we can see that @Test annotation is followed by a parameter, called timeout. Timeout is an optional parameter supported by @Test annotation that causes a test to fail if it takes longer than the specified amount of time (measured in milliseconds).

For further details regarding the @Test annotation, the assertArrayEquals assertion (which are also mentioned in our code) and other JUnit Assertions and Annotations, you can have a look at JUnit using Assertions and Annotations Example.

3. Run your test case from the command line

You can run your JUnit test outside Eclipse, by using the org.junit.runner.JUnitCore class. This class provides the runClasses() method which allows you to execute one or several test classes. The return type of runClasses() method is an object of the type org.junit.runner.Result. This object can be used to collect information about the tests. Also, in case there is a failed test, you can use the object org.junit.runner.notification.Failure which holds description of the failed tests.

The procedure below shows how to run your test outside Eclipse.

In the directory JUnitTest, use a text editor and create a new Java class named JunitTestRunner.java with the following code.

JunitTestRunner.java

import org.junit.runner.JUnitCore;
import org.junit.runner.Result;
import org.junit.runner.notification.Failure;

public class JunitTestRunner {

	public static void main(String[] args) {

		Result result = JUnitCore.runClasses(JunitTest.class);
		for (Failure fail : result.getFailures()) {
			System.out.println(fail.toString());
		}
		if (result.wasSuccessful()) {
			System.out.println("All tests finished successfully...");
		}else{
			System.out.println("The test failed..");
		}
	}
}
  • Open command prompt and move down directories so as to find the directory where your java classes are located:
C:\Users\konstantina>cd JUnitTest

Attention: If your classes are located inside a package, for example package com.javacodegeeks.core.junit, you can have a look at JUnit Ignore Test Example, where we describe exactly what you should do in that case.

  • When JUnitTest is your current directory, compile all the classes in the direcory

Attention: To run your JUnit tests outside Eclipse properly you need to add the needed JUnit library jars to the classpath of your program. You can find those library jars here.

C:\Users\konstantina\JUnitTest>javac -classpath "C:\Users\konstantina\Downloads\junit-4.11.jar";"C:\Users\konstantina\Downloads\hamcrest-core-1.3.jar"; FirstDayAtSchool.java JunitTest.java JunitTestRunner.java
  • Now run the JunitTestRunner
C:\Users\konstantina\JUnitTest>java -classpath "C:\Users\konstantina\Downloads\junit-4.11.jar";"C:\Users\konstantina\Downloads\hamcrest-core-1.3.jar"; JunitTestRunner

  • Output:
Inside testPrepareMyBag()
Preparing my bag
Inside printItems()
My school bag contains: [Books, Notebooks, Pens]
testPrintItems(JunitTest): test timed out after 100 milliseconds
The test failed..

As we see in the output, the first test case testPrepareMyBag() was executed successfully but the second test case testPrintItems() was automatically marked as failed, because its execution took longer than 100 milliseconds, which was the specified number in timeout parameter.

Download the source code

This was an example of timeout parameter, which is supported by @Test annotation in JUnit testing framework.
Download the source code of this example : JUnitTest.zip

(No Ratings Yet)
Start the discussion Views Tweet it!

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you our best selling eBooks for FREE!

 

1. JPA Mini Book

2. JVM Troubleshooting Guide

3. JUnit Tutorial for Unit Testing

4. Java Annotations Tutorial

5. Java Interview Questions

6. Spring Interview Questions

7. Android UI Design

 

and many more ....

 

Receive Java & Developer job alerts in your Area

 

Leave a Reply

avatar
  Subscribe  
Notify of