Book Image


Book Image


Overview of this book

Table of Contents (19 chapters)
Spring Cookbook
About the Author
About the Reviewers

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:

  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 example, the class we test, NumberUtil, is in the src/main/java folder, in the com.spring_cookbook.util package. Our corresponding test class will be in the src/test/java folder...