Intro
Unit testing is an integral part of writing clean, secure, bug-free code. JUnit is a testing framework built for testing Java.
Setup
To test a class in Intelli J, open the class and place the caret within it
Here's our sample class:
public class Person {
private int age;
public void setAge(int age) { this.age = age; }
public int doubleAge() {
return age * 2;
}
}
- It's best to keep things organized so create a directory as a child of the root named test
- Right-click the directory and choose Mark Directory as > => Test Sources Root
- Navigate to the menubar Navigate => Test or use the shortcut -> ctrl + shift + t and select Create New Test... from the context menu
- A Create Test dialog will pop up
-
Choose your testing library - JUnit5 is good
If it says that the JUnit5 library is no found in the module you'll need to import it- Click Fix
- This will open a Download Library from Maven Repository dialog
- The or.junit.jupiter:junit-jupiter:5.4.2 library should already be selected
- Select where you want it downloaded to
- Choose whether you want to include the Sources, Javadocs, or Annotations
- Click OK
- If you'd like Intelli J to generate setUp/tearDown methods, check the appropriate boxes
- Select the methods you want generated for you
- Click OK
This will generate the following code:
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
public class PersonTest {
@BeforeEach
void setUp() {
}
@AfterEach
void tearDown() {
}
@Test
void doubleAge() {
}
}
If you'll have more than one testing method, rename the test method to make it clear what it is testing
Note that you'll have to Edit the Configuration so that the new name is referenced properly
@Test
void testPositive_doubleAge() {
}
public class PersonTest {
Person p;
@BeforeEach
void setUp() {
p = new Person();
}
@AfterEach
void tearDown() {
}
@Test
void testPositive_doubleAge() {
p.setAge(40);
int expectedResult = 80;
int actualResult = p.DoubleAge();
assertEquals(expectedResult, actualResult);
}
}
Now it's easy to copy/paste that test to create more tests:
@Test
void testNegative_doubleAge() {
p.setAge(-40);
int expectedResult = 0;
int actualResult = p.DoubleAge();
assertEquals(expectedResult, actualResult);
}
Run the Tests
In the Run panel, right-click the test class and select Run '[test_class_name]' or use the shortcut -> ctrl + shift + F10
This will show us that one of our tests passed and one of our tests failed. The logic in our Person class is faulty. It does not handle negative numbers.