How to Create simple JUnit test case in Eclipse





Hey guys in this post, we will create simple JUnit test case for adding 2 numbers in Eclipse with step by step example

Overview


  • @Test annotation is used to unit test a particular method
  • assertEquals() method is used to check both the values

Create Java Project


Create a Java project and enter the project name: Junit-tutorial

01
Create a new source folder on the root of the project, to keep all the Junit test files.

02
Create a new class


Inside the src folder, create a package in.bushansirgur.junit and create a new Java class Calculate.

package in.bushansirgur.junit;

public class Calculate {
	
	public int addTwoNumbers(int a, int b) {
		return a + b;
	}
}

Inside the class, we have defined a new method addTwoNumbers() takes in 2 numbers, which will return the sum of 2 numbers.

Create a JUnit test class


Inside test folder, create a package in.bushansirgur.junit and create a new Java class CalculateTest. Generally, developers will append the keyword Test to the end of the class names as its a good practice.

package in.bushansirgur.junit;

import static org.junit.Assert.*;

import org.junit.Test;

public class CalculateTest {

	@Test
	public void addTwoNumbersTest() {
		Calculate calculate = new Calculate();
		int total = calculate.addTwoNumbers(2, 4);
		assertEquals(6, total);
	}

}

We have created a method addTwoNumbersTest(), inside this we will create an instance of Calcalute class and call the method addTwoNumbers().

We will call assertEquals() method to check the expected value and actual value.

Run the Test class


Run the application using the below maven command –

mvn clean test -Dtest=in.bushansirgur.junit.CalculateTest

If it shows green bar then all the test cases are run successfully
05

More assert methods


Apart from assertEquals() method, JUnit provides bunch assert methods to do the unit testing. Some of them are as follows

  • assertTrue() Asserts that a condition is true. If it isn’t it throws an AssertionError without a message.
  • assertFalse() Asserts that a condition is false. If it isn’t it throws an AssertionError without a message.
  • assertNotEquals() Asserts that two longs are not equals. If they are, an AssertionError without a message is thrown.
  • assertNull() Asserts that an object is null. If it isn’t an AssertionError is thrown.
  • assertNotNull() Asserts that an object isn’t null. If it is an AssertionError is thrown.
  • assertArrayEquals() Asserts that two boolean arrays are equal. If they are not, an AssertionError is thrown. If expected and actual are null, they are considered equal.




About the author

Bushan Sirgur

Hey guys, I am Bushan Sirgur from Banglore, India. Currently, I am working as an Associate project in an IT company.

View all posts

Leave a Reply

Your email address will not be published. Required fields are marked *