Unit testing with JUnit 4

JUnit, first released in 2000, is the most widely used Java unit testing framework. Eclipse supports it out of the box.

In this recipe, we will write and execute a JUnit 4 test.

Getting ready

In this recipe, we'll test this simple method (located in the NumberUtil class), which adds two integers:

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

How to do it…

Follow these steps to test a method with JUnit 4:

  1. Add the junit Maven dependency in pom.xml:
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.10</version>
      <scope>test</scope>
    </dependency>
  2. Create a Java package for your test classes. The standard practice is to keep the test classes in a separate folder with the same package structure. For ...

Get Spring Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.