org.junit

The org.junit package is the root package of an open source testing framework JUnit. It can be added to the project as the following pom.xml dependency:

<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>

The scope value in the preceding dependency tag tells Maven to include the library .jar file only when the test code is going to be run, not into the production .jar file of the application. With the dependency in place, you can now create a test. You can write code yourself or let IDE do it for you using the following steps:

  1. Right-click on the class name you would like to test
  2. Select Go To
  3. Select Test
  4. Click Create New Test
  1. Click the checkbox for the methods of the class you would like to test
  2. Write code for the generated test methods with the @Test annotation
  3. Add methods with @Before and @After annotations if necessary

Let's assume we have the following class:

public class SomeClass {
public int multiplyByTwo(int i){
return i * 2;
}
}

If you follow the preceding steps listed, the following test class will be created under the test source tree:

import org.junit.Test;
public class SomeClassTest {
@Test
public void multiplyByTwo() {
}
}

Now you can implement the void multiplyByTwo() method as follows:

@Test
public void multiplyByTwo() {
SomeClass someClass = new SomeClass();
int result = someClass.multiplyByTwo(2);
Assert.assertEquals(4, result);
}

A unit is a minimal piece of code that can be tested, thus the name. The best testing practices consider a method as a minimal testable unit. That's why a unit test usually tests a method.