Now that you have installed JUnit with the last tutorial , we will be ready to test it.

So, go!

Open Eclipse, select a project, then create a new Class.
In your example, it will be a class with classical mathematical operations.
So let’s name it MyOperations.

We don’t need a package for this tutorial JUnit for beginners, so here the code of this class:

/**
*
* Classical mathematical operations
* @author BadproG
*
*/
public class MyOperations {
	/**
	* Classical addition
	* @param x
	* @param y
	* @return
	*/
	public int addition(int x, int y) {
		return x + y;
	}
	/**
	* Classical division
	* @param x
	* @param y
	* @return
	*/
	public int division(int x, int y) {
		return x / y;
	}
	/**
	* Classical modulo
	* @param x
	* @param y
	* @return
	*/
	public int modulo(int x, int y) {
		return x % y;
	}
	/**
	* Classical multiplication
	* @param x
	* @param y
	* @return
	*/
	public int multiplication(int x, int y) {
		return x * y;
	}
	/**
	* Classical subtraction
	* @param x
	* @param y
	* @return
	*/
	public int subtraction(int x, int y) {
		return x - y;
	}
}

As you can see, these methods are really easy to understand.

Let’s continue by creating a JUnit Test Case (right click on the default package > New > JUnit Test Case).

In the Name input, type MyOperationsTest then at the end, fill the Class under test input with MyOperations.
Click Next and select all methods from MyOperations class, such as addition(int, int), division(int, int), etc.
Click Finish.

OK, now right click this file (MyOperationsTest) > Run As > JUnit Test.

A new window appears, this is the JUnit one, and all testd are in red! Oh my God, what’s going on?

No panic, it is normal.

Indeed, all tests in your class (MyOperationsTest) are fail(“Message”) methods.
It means that they are programmed to fail your tests.

So replace all these methods by the following ones:

import static org.junit.Assert.*;
import org.junit.Test;
public class MyOperationsTest {
    
    @Test
    public void testAddition() {
        MyOperations tester = new MyOperations();
        assertEquals(15, tester.addition(5, 10));
    }
    
    @Test
    public void testDivision() {
        MyOperations tester = new MyOperations();
        assertEquals(2, tester.division(10, 5));
    }
    
    @Test
    public void testModulo() {
        MyOperations tester = new MyOperations();
        assertEquals(1, tester.modulo(10, 3));
    }
    
    @Test
    public void testMultiplication() {
        MyOperations tester = new MyOperations();
        assertEquals(1000, tester.multiplication(25, 40));
    }
    
    @Test
    public void testSubstraction() {
        MyOperations tester = new MyOperations();
        assertEquals(47, tester.subtraction(50, 3));
    }
}

Re Run As the JUnit Test and this time all tests will be in green!

You have just performed your first test unit.
Well done.