Junit simple test

This example shows how to write a simple test using Junit 4. @Test has two optional parameters, expected and timeout. It also tells JUnit that the public void method to which it is attached can be run as a test case. In the snippet below we have created a calculator in which we want to validate the behavior of the add method. To do so, we will write a unit test that calls Calculator.add and asserts that the value equals 15.

Setup

Simple calculator class

static class Calculator {

    public static int add(int a, int b) {
        return a + b;
    }
}

Calculator add

@Test
public void calculator_add () {
    int calculatedValue = Calculator.add(5,  10);
    assertEquals(15, calculatedValue);
}