Introduction to JUnit

Introduction to Testing in Java

Maria Milusheva

Senior Software Engineer

Quick facts

  • JUnit is the most popular Java testing library
  • It is well-maintained and constantly updated

An image of the JUnit 5 logo.

Introduction to Testing in Java

Writing a JUnit test

Let's write a test for the addTwoNumbers() method:

public int addTwoNumbers(int a, int b) {
    return a + b;
}
Introduction to Testing in Java

JUnit @Test annotation

  • Install JUnit using an IDE or build tools (example in the citation)

  • Every test must have the @Test annotation:

import org.junit.jupiter.api.Test;

@Test 
// Test method will be here

Annotation - special metadata that indicates how the method should be handled by compilers and frameworks. Annotations begin with @

1 https://www.jetbrains.com/help/idea/junit.html
Introduction to Testing in Java

JUnit test structure

import org.junit.jupiter.api.Test;

@Test 

void testAddTwoNumbers() {
// Arrange - Given int num1 = 2; int num2 = 2;
// Act - When int actual = addTwoNumbers(num1, num2);
// Assert - Then assertEquals(4, actual); }
Introduction to Testing in Java

Assert statements

  • Quick way to compare actual outcomes to expected outcomes
  • If expected and actual outcomes don't match, test fails
  • Help quickly catch bugs and errors

Graphics representing assert statement

Introduction to Testing in Java

Test outcomes

Consider the assertion:

assertEquals(4, actual); // Will succeed if actual == 4

If successful, will produce a Test passed message

If the values are not equal, e.g. actual = 5:

org.opentest4j.AssertionFailedError: expected: <4> but was: <5>

Remember argument order! First argument is the expected one in JUnit.

Introduction to Testing in Java

Additional test for overflow

@Test 

void testAddTwoNumbers() { // Given int num1 = 2147483647; int num2 = 1; // When int actual = addTwoNumbers(num1, num2); // Then assertEquals(-2147483648, actual); }
Introduction to Testing in Java

Notes about JUnit and testing

  • There can be multiple assertions per test
  • All assertions need to succeed in order for the test to pass
  • We can import all assertions using:
import org.junit.jupiter.api.Assertions.*;
Introduction to Testing in Java

More notes

  • Following is a custom Datacamp tool, not needed in IDE:
import static com.datacamp.util.testing.CustomJUnitTestLauncher.launchTestsAndPrint;
  • import static package.Class.method allows using method as just method, without writing package.Class.method
import static java.lang.Math.max;

...

max(3,5); // Instead of Math.max(3, 5)
Introduction to Testing in Java

Let's practice!

Introduction to Testing in Java

Preparing Video For Download...