junit

JUnit Exceptions Test Example

In this example we are going to see how to use @Test annotation along with its optional parameter expected 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 JUnitExceptions. 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

import java.util.Arrays;

public class FirstDayAtSchool {

	public String[] prepareMyBag() {
		String[] schoolbag = { "Books", "Notebooks", "Pens" };
		System.out.println("I put in my bag: "+Arrays.toString(schoolbag));
		return (schoolbag);
	}

	public void printItems(String []items) {
		
		System.out.println("The last item I put in my bag was: " +items[items.length]);
		
	}
}

2. Create JUnit test case

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

JunitExceptionsTest1.java

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

public class JunitExceptionsTest1 {

	FirstDayAtSchool school = new FirstDayAtSchool();
	String[] bag = { "Books", "Notebooks", "Pens" };

	@Test
	public void testPrepareMyBag() {
		System.out.println("Inside testPrepareMyBag()");
		assertArrayEquals(bag, school.prepareMyBag());
	}

	@Test(expected = ArrayIndexOutOfBoundsException.class)
	public void testPrintItems() {
		System.out.println("Inside printItems()");
		school.printItems(bag);
	}
}

In the same way, create another class named JunitExceptionsTest2.java with similar code, where the only difference with the previous class will be the declared exception.

JunitExceptionsTest2.java

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

public class JunitExceptionsTest2 {

	FirstDayAtSchool school = new FirstDayAtSchool();
	String[] bag = { "Books", "Notebooks", "Pens" };

	@Test
	public void testPrepareMyBag() {
		System.out.println("Inside testPrepareMyBag()");
		assertArrayEquals(bag, school.prepareMyBag());
	}

	@Test(expected = ArithmeticException.class)
	public void testPrintItems() {
		System.out.println("Inside printItems()");
		school.printItems(bag);
	}
}

In the method testPrintItems() in both java classes, we can see that @Test annotation is followed by a parameter, called expected. The expected is an optional parameter supported by @Test annotation which declares that a test method should throw an exception. If it doesn’t throw an exception or if it throws a different exception than the one declared, the test fails, otherwise it succeeds.

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 cases 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 JUnitExceptions, use a text editor and create a new Java class named JunitExceptionsTestRunner.java with the following code.

JunitExceptionsTestRunner.java

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

public class JunitExceptionsTestRunner {

	public static void main(String[] args) {

		Result result = JUnitCore.runClasses(JunitExceptionsTest1.class);
		for (Failure fail : result.getFailures()) {
			System.out.println(fail.toString());
		}
		if (result.wasSuccessful()) {
			System.out.println("All tests finished successfully...");
		}
	}
}

We will first run the JunitExceptions1.java, so the argument of runClasses method will be the perspective class.

  • Open command prompt and move down directories so as to find the directory where your java classes are located:
C:\Users\konstantina>cd JUnitExceptions

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 JUnitExceptions is your current directory, compile all the classes in the directory

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\JUnitExceptions>javac -classpath "C:\Users\konstantina\Downloads\junit-4.11.jar";"C:\Users\konstantina\Downloads\hamcrest-core-1.3.jar"; FirstDayAtSchool.java JunitExceptionsTest1.java JunitExceptionsTest2.java JunitExceptionsTestRunner.java
  • Now run the JunitExceptionsTestRunner
C:\Users\konstantina\JUnitExceptions>java -classpath "C:\Users\konstantina\Downloads\junit-4.11.jar";"C:\Users\konstantina\Downloads\hamcrest-core-1.3.jar"; JunitExceptionsTestRunner

  • Output:
Inside testPrepareMyBag()
I put in my bag: [Books, Notebooks, Pens]
Inside printItems()
All tests finished successfully...

As we see in the output, both tests finished successfully, although the second test case throws exception. The reason for this is that the thrown exception is the one declared in the expected, so the test doesn’t fail, it is just ignored.

Now, let’s run the second test case JunitExceptionsTest2.java. We will make a small change in the code of JunitExceptionsTestRunner.java, so as to include the other class in runClasses method.

JunitExceptionsTestRunner.java

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

public class JunitExceptionsTestRunner {

	public static void main(String[] args) {

		Result result = JUnitCore.runClasses(JunitExceptionsTest2.class);
		for (Failure fail : result.getFailures()) {
			System.out.println(fail.toString());
		}
		if (result.wasSuccessful()) {
			System.out.println("All tests finished successfully...");
		}
	}
}

In the same way as before, we compile and run our classes.

  • Compile all java classes in JUnitExceptions directory.
C:\Users\konstantina\JUnitExceptions>javac -classpath "C:\Users\konstantina\Downloads\junit-4.11.jar";"C:\Users\konstantina\Downloads\hamcrest-core-1.3.jar"; FirstDayAtSchool.java JunitExceptionsTest1.java JunitExceptionsTest2.java JunitExceptionsTestRunner.java
  • Now run again the JunitExceptionsTestRunner.
C:\Users\konstantina\JUnitExceptions>java -classpath "C:\Users\konstantina\Downloads\junit-4.11.jar";"C:\Users\konstantina\Downloads\hamcrest-core-1.3.jar"; JunitExceptionsTestRunner

  • Output:
Inside testPrepareMyBag()
I put in my bag: [Books, Notebooks, Pens]
Inside printItems()
testPrintItems(JunitExceptionsTest2): Unexpected exception, expected<java.lang.ArithmeticException> but was<java.lang.ArrayIndexOutOfBoundsException>

As we see in the output, the first test case succeeds but the second test case fails, as the exception of our code should be the ArrayIndexOutOfBoundsException but the expected parameter declared ArithmeticException as the expected exception.

Download the source code

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

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.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments
Back to top button