Java Unit Testing – TDD in practical examples

Hi!
In this post, I will tell you something about unit testing in Java. We will use JUnit 5 library. Our work will be base on Test-Driven Development principles. The best way to learn something is practice and that’s why all these things I will present you with practical examples. I encourage you to try write test by yourself. You can find the repository with a code on my GitHub: https://github.com/Chinet1/JavaTDD

The major property of TDD is very short development cycle. Authors of book “Test-driven Java Development” named it “Red-Green-Refactor”. What is it mean? We write the test that must fail and after this, we write code that makes test “green”. The code would be simple as possible. Now, in step number three we make refactoring and we improve the code without fear that something goes wrong.
Ok, let’s make this in practice.

Calculator

We are going to make simple calculator class.

First requirement:

Calculator status is true when initialized correctly.
Let’s write the first test in CalculatorTest class.

@Test
public void whenCalculatorInitializedThenReturnTrue() {
    Calculator calculator = new Calculator();
        
    assertTrue(calculator.getStatus());
}

In the first line, you can see the annotation that says to the compiler: “This is test method”. The name of the method should have enough information to know what this code testing. Use words: “when”, “then”. To check if method returned true we will use the assertTrue method.
Now let’s write code that will make test true.

private boolean status;

public Calculator() {
    this.status = true;
}

public boolean getStatus() {
    return status;
}

Run test class to check if everything is alright. How good to see a green line!

Requirement 2:

The calculator must have addition and subtraction functions.
Test:

@Test
public void whenAdditionTwoNumberThenReturnCorrectAnswer() {
    Calculator calculator = new Calculator();
        
    assertEquals( 5, calculator.addition(2,3));
}

Next often used method assertEquals. This method checking if the first argument is equal to a second argument.
Implementation is very easy to write and looks that:

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

Maybe you note that we initialize calculator class in each method, in this case, that’s not a good idea. Let’s make us first refactoring. We will use “@BeforeAll” annotation to write a method that will be executed first before test method.

private static Calculator calculator;

@BeforeAll
public static void init(){
    calculator = new Calculator();
}

Now you can delete all calculator initialization code in test methods.  Make the subtraction function implementation on your own. You can check out your code with my that is on my Github repository.

Requirement 3:

The calculator must have division function. When someone divides by zero, an exception should be thrown.
Let’s write the first test to this requirement. There is no rocket science here.

@Test
public void whenDivisionThenReturnCorrectAnswer() {
    assertEquals(2, calculator.division(8, 4));
}

Implementation is also easy.

public int division(int a, int b) {
    return a / b;
}

And now something new! We must check that exception is thrown when someone divides by zero.

@Test
public void whenDivisionByZeroThenThrowException() {
    Throwable exception = assertThrows(IllegalArgumentException.class, () -> {
        calculator.division(5, 0);
    });
    assertEquals("Cannot division by zero", exception.getMessage());
}

We use assertThrows with Lambda from Java 8 to use division function in controlled conditions and wait for IllegalArgumentException. At the end, we check exception message in the assertEquals method.
Now we can change division method in Calculator class.

public int division(int a, int b) {
    if (b == 0) {
        throw new IllegalArgumentException("Cannot division by zero");
    } else {
        return a / b;
    }
}

If you run the test you can immediately check if changes you made don’t break other functionality of the method. That’s why you should write unit test. When you change the code, you can check if it still works like before.

That’s all for now! You can add more function to Calculator class using TDD principles on your own. Hope this article was helpful and encourage you to explore the topic of unit testing.

Be First to Comment

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.