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:
Add the
junit
Maven dependency inpom.xml
:<dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.10</version> <scope>test</scope> </dependency>
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 thesrc/main/java
folder, in thecom.spring_cookbook.util
package. Our corresponding test class will be in thesrc/test/java
folder...