Hey guys in this post, we will create simple JUnit test case for adding 2 numbers in Eclipse with step by step example
Table of Contents
Overview
@Testannotation is used to unit test a particular methodassertEquals()method is used to check both the values
Create Java Project
Create a Java project and enter the project name: Junit-tutorial

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

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

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 anAssertionErrorwithout a message.assertFalse()Asserts that a condition is false. If it isn’t it throws anAssertionErrorwithout a message.assertNotEquals()Asserts that two longs are not equals. If they are, anAssertionErrorwithout a message is thrown.assertNull()Asserts that an object is null. If it isn’t anAssertionErroris thrown.assertNotNull()Asserts that an object isn’t null. If it is anAssertionErroris thrown.assertArrayEquals()Asserts that two boolean arrays are equal. If they are not, anAssertionErroris thrown. Ifexpectedandactualarenull, they are considered equal.
