Home | License | FAQ | Contact | Smart-API

Last Updated: October 20, 2022

How to Create JUnit Test

In this tutorial, we will show you how Create and use JUnit Test.

JUnit is an open-source framework for unit testing Java programs.

This framework is used by developers to create and run automated tests. Every time new code is added, certain test cases in Java need to be run again. To make sure that the code is not broken, this is done.

Pre-Requisite:

Steps:

1.Create class with add method.
  1. Create a package

  2. Create a class.

  3. Create a sum method in the class, as shown in the figure below.

This method will take two parameters and return the value of the summation of two numbers.

You can copy the code below and paste it into your project and it will auto-create a class for you.
package app;

public class App {

	public int sum(int numberA, int numberB) {
		return (numberA + numberB);
	}
}
project-screen1.png
Figure 1. App Java File
2.Create new JUnit Test Case.

Now we need to create the class test case that we will use in our project.

  1. Right-click on the Project.

  2. Select new.

  3. Select Junit Test Case.

We are Using JUnit 4 in our tutorial.
junit-create-screen5.png
Figure 2. Create JUnit
  1. Enter the package name.

  2. Enter class name.

Now let us create our test Methods like the figure below.

apptest-screen6.png
Figure 3. JUnit File
package calculator;

import static org.junit.Assert.assertEquals;

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

import app.App;

public class AppTest {

	private App app;

	@Before
	public void setUp() throws Exception {
		app = new App();
	}

	@Test
	public void testSum() {
		assertEquals(10, app.sum(5, 5));
	}
}

In the Method "testSum" we used "assertEquals", which will we use to compare the expected result with the actual result.

method-screen10.png
Figure 4. testAdd Method
3.Run the Junit Test.
  1. Right-Click on the project.

  2. Select Run As.

  3. Select JUnit Test.

junit-run-screen7.png
Figure 5. Running successfully

Our Test runs successfully as shown in the figure above with no errors.

As you can see it shows us the time take to run the method, in which class, how many time it runs, and the number of errors and failures.

Let us try adding a new test Method with the wrong data.

@Test
	public void testAddWrongNumbers() {
		assertEquals(20, app.sum(5, 5));
	}
junit-screen8.png
Figure 6. JUnit file with wrong expected data

Repeat the last step Run as JUnit Test again.

junit-run2-screen9.png
Figure 7. JUnit Running

Here we got a failure because our expected result is 20 and the actual result is 10, So our test Method is working and can detect failure.

Advanced JUnit example with Exception Handling

If the code you runs throws an exception it will automatically fail your unit test, so we use assertThrows method.

If the code did not return an exception, the error "Expected exception" shows up.

Steps:

1.Create class with add method.

Ok, let’s start with creating the method in our class, like in step 1 in the previous example.

Our method returns the age group ("Infants","Child","Teen","Adult") when we pass the age.

package app;

public class AdvancedApp {

	public String age(int age) {

		if (age <= 0) {
			throw new IllegalArgumentException("invalid input");
		}
		if (age > 0 && age <= 4) {
			return "Infants";
		}
		if (age >= 5 && age <= 12) {
			return "Child";
		}
		if (age >= 13 && age <= 19) {
			return "Teen";
		}
		return "Adult";
	}
}
2.Create new JUnit Test Case.

We create a new JUnit Test Case as step 2 in the previous example.

package calculator;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThrows;

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

import app.AdvancedApp;

public class AdvancedAppTest {

	private AdvancedApp app;

	@Before
	public void setUp() throws Exception {
		app = new AdvancedApp();
	}

	@Test
	public void ageThree() {
		assertEquals("Infants", app.age(3));
	}

	@Test
	public void ageFive() {
		assertEquals("Child", app.age(5));
	}

	@Test
	public void ageThirteen() {
		assertEquals("Teen", app.age(13));
	}

	@Test
	public void ageTwentyOne() {
		assertEquals("Adult", app.age(21));
	}

	@Test(expected = IllegalArgumentException.class)
	public void ageNegativeOne() {
		app.age(-1);// Throws an Exception
	}

}
We added (expected = IllegalArgumentException.class) after test annotation ("@Test"), because we know the method will return an exception, if you remove it, we get "IllegalArgumentException :invalid input" when we run the JUnit test.
junit-invalid-screen12.png
Figure 8. Error
3.Run the Junit Test.

We Run the Junit test as in step 3 in the previous example.

junit-screen11.png
Figure 9. Running successfully

As you can see we did not got any exception because in our test method we predicted the exception.

That’s how we handle the exceptions with JUnit.

JUnit Test Order

By default, JUnit runs tests in an unpredictable order.

In most cases, this behavior is perfectly fine and acceptable. But there are cases when we need to force a specific order, so we can Use Order by name ascending.

Steps:

1.Add the @FixMethodOrder annotation before the class.
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
2.Add alphabetical order to the methods.

NOTE: We are using Advanced JUnit example with Exception Handling for this example.

If you run the JUnit test repeatedly the methods will be executed randomly, as shown in the figure below.

junit-screen11.png
Figure 10. Random Order

So let’s add ("A","B","C",etc.) to the start of the method as shown in the code below.

package calculator;

import static org.junit.Assert.assertEquals;

import org.junit.Before;
import org.junit.FixMethodOrder;
import org.junit.Test;
import org.junit.runners.MethodSorters;

import app.AdvancedApp;

@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class AdvancedAppTestOrder {

	private AdvancedApp app;

	@Before
	public void setUp() throws Exception {
		app = new AdvancedApp();
	}

	@Test
	public void A_ageThree() {
		assertEquals("Infants", app.age(3));
	}

	@Test
	public void B_ageFive() {
		assertEquals("Child", app.age(5));
	}

	@Test
	public void C_ageThirteen() {
		assertEquals("Teen", app.age(13));
	}

	@Test
	public void D_ageTwentyOne() {
		assertEquals("Adult", app.age(21));
	}

	@Test(expected = IllegalArgumentException.class)
	public void E_ageNegativeOne() {
		app.age(-1);// Throws an Exception
	}

}
3.Run the JUnit test again.

As you see in the figure below, no matter how many time you run the test, the excute order always will be the same.

junit-order-screen13.png
Figure 11. Ordered by name

That’s how we run the JUnit test in order.


The End


Home | License | FAQ | Contact | Smart-API