JUnit is a popular unit testing framework for Java applications. IntelliJ IDEA provides excellent support for creating, running, and debugging JUnit tests with features like:
For Maven projects, add this to your pom.xml:
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
<version>5.8.2</version>
<scope>test</scope>
</dependency>
For Gradle projects, add this to your build.gradle:
testImplementation 'org.junit.jupiter:junit-jupiter:5.8.2'
IntelliJ IDEA comes with bundled JUnit libraries. You can also use these without adding dependencies by configuring the test framework in Project Structure (⌘; on Mac or Ctrl+Alt+Shift+S on Windows/Linux).
Create a new class in your test directory (src/test/java) with naming convention:
OriginalClassName + "Test" (e.g., CalculatorTest)
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
class CalculatorTest {
@Test
void testAdd() {
Calculator calculator = new Calculator();
assertEquals(5, calculator.add(2, 3), "2 + 3 should be 5");
}
}
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
class StringUtilsTest {
@Test
void testIsEmpty() {
assertTrue(StringUtils.isEmpty(""));
assertFalse(StringUtils.isEmpty("text"));
}
@Test
void testReverse() {
assertEquals("cba", StringUtils.reverse("abc"));
assertNull(StringUtils.reverse(null));
}
}
| Assertion | Description |
|---|---|
assertEquals(expected, actual) |
Tests if two values are equal |
assertTrue(condition) |
Tests if condition is true |
assertFalse(condition) |
Tests if condition is false |
assertNull(object) |
Tests if object is null |
assertNotNull(object) |
Tests if object is not null |
assertThrows(exception, executable) |
Tests if code throws expected exception |
| Annotation | Description |
|---|---|
@BeforeEach |
Executed before each test method |
@AfterEach |
Executed after each test method |
@BeforeAll |
Executed once before all test methods |
@AfterAll |
Executed once after all test methods |
@DisplayName |
Custom display name for test class or method |
mvn test or Gradle: gradle test@ParameterizedTest
@ValueSource(ints = {1, 3, 5, -3, 15})
void testIsOdd(int number) {
assertTrue(MathUtils.isOdd(number));
}
@Test
void testUserService() {
// Create mock
UserRepository mockRepo = Mockito.mock(UserRepository.class);
// Define mock behavior
when(mockRepo.findById(1L)).thenReturn(new User(1L, "test@example.com"));
// Inject mock and test
UserService service = new UserService(mockRepo);
User user = service.getUserById(1L);
assertEquals("test@example.com", user.getEmail());
verify(mockRepo).findById(1L);
}
@Test
void testWithdrawalFailsWhenBalanceInsufficient() {
BankAccount account = new BankAccount(100);
assertThrows(InsufficientFundsException.class, () -> {
account.withdraw(200);
});
}
Ctrl+Shift+T (Windows/Linux) or ⌘⇧T (Mac) to quickly navigate between test and production code
My simple library
..of useful code