Book Image

SPRING COOKBOOK

By : Jerome Jaglale, Yilmaz
Book Image

SPRING COOKBOOK

By: Jerome Jaglale, Yilmaz

Overview of this book

This book is for you if you have some experience with Java and web development (not necessarily in Java) and want to become proficient quickly with Spring.
Table of Contents (14 chapters)
13
Index

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 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...