Basic JUnit 5

I have tried learning from various tutorials for JUnit and all tutorials went into unnecessary aspects of JUnit which are useful but not for someone who is looking to grab JUnit understanding quickly and knows Java. So I am writing this tutorial for someone who is looking to grab JUnit concepts and knows Java.

Let’s start with basic JUnit test. Let’s write a method that takes in 2 integers and returns sum of it. Your java class will look like this.

package org.junittutorial;

public class SimpleClass {
    public static int add(int x, int y) {
        return (x + y);
    }
}

Now, to write JUnit for this class, we will create new class as SimpleClassTest.

We will create unit test method with descriptive name of what test is intended to check. In our case, “should return addition when given two integers” describes method name, so our method name is should_return_addition_when_given_two_integers.

We divide unit test method in “given”, “when”, “then” format.

In our case, we want to test given 2 integers, x as 2 and y as 3, are we getting expected sum as 5(expectedSum).
To check this, we will fire method in “when” section of test and check for actualSum.

Then we will assert if both values are same in “then” section of test case.
If assertion fails, JUnit test for this method will fail.
If it succeeds, then JUnit test will pass.

Your final JUnit test class will look as follows:

package org.junittutorial;

import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
class SimpleClassTest {

@Test
void should_return_addition_when_given_two_integers() {
        // given
        int x = 2;
        int y = 3;
        int expectedSum = 5;

        // when
        int actualSum = SimpleClass.add(x, y);

        // then
        assertEquals(expectedSum, actualSum);
    }
}

Comments

Leave a Reply

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