Unit Testing in Java with JUnit 4

Tiempo de lectura: 2 minutos

Reading time: 3 minutes

Today, I’m going to show you how you can implement JUnit tests in Java with a simple example.

The first thing you need to do is to start a Java project and create an example class called Multiplication:

Now let’s create a simple function for multiplication:

public class Multiplication {

}

Next, in this skeleton, let’s implement the JUnit test:

@Test

public void testMultiplication() {
    Multiplication multiplication = new Multiplication();
    int result = multiplication.multiply(2, 2);
    int expected = 4;
    assertEquals(expected, result);
}

The test is straightforward. First, we instantiate the Multiplication object we created. Then we perform a multiplication of 2*2 and store the result in a variable. We create a variable to indicate the expected result. We call the JUnit’s assertEquals method to check that the expected result matches the result of the method. And we execute the test:

  • Right-click, Run as > JUnit Test

If the test has passed, it will appear in green:

And now, in this skeleton, let’s implement the JUnit test:

@Test

public void testMultiplication() {
    Multiplication multiplication = new Multiplication();
    int result = multiplication.multiply(2, 2);
    int expected = 4;
    assertEquals(expected, result);
}

The test is straightforward. First, we instantiate the Multiplication object we created. Then we perform a multiplication of 2*2 and store the result in a variable. We create a variable to indicate the expected result. We call the JUnit’s assertEquals method to check that the expected result matches the result of the method. And we execute the test:

  • Right-click, Run as > JUnit Test

If the test has passed, it will appear in green:

Leave a Comment