In Java testing (especially with JUnit and Mockito), annotations are used to mark test methods, configure lifecycle events, inject mocks, and more.
Here’s a comprehensive list of commonly used annotations in Java tests:
✅ JUnit Annotations
▶️ Core Test Annotations
Annotation | Purpose | Example |
---|
@Test | Marks a method as a test | @Test void testAddition() { ... } |
@BeforeEach | Runs before each test method | @BeforeEach void setUp() { ... } |
@AfterEach | Runs after each test method | @AfterEach void tearDown() { ... } |
@BeforeAll | Runs once before all test methods | @BeforeAll static void init() { ... } |
@AfterAll | Runs once after all test methods | @AfterAll static void cleanup() { ... } |
@Disabled | Disables a test or test class | @Disabled("Broken test") |
▶️ Assertions and Parameterized Tests
Annotation | Purpose |
---|
@DisplayName | Sets a custom name for the test |
@ParameterizedTest | Runs the same test with different inputs |
@ValueSource | Supplies literal values for parameterized tests |
@CsvSource , @MethodSource | Provide complex parameter sets |
✅ Mockito Annotations
Annotation | Purpose |
---|
@Mock | Creates a mock object |
@InjectMocks | Injects mock fields into the test subject |
@Spy | Creates a spy (partial mock) |
@Captor | Declares an ArgumentCaptor |
@MockBean | (Spring) Mocks a bean in Spring context |
🔧 Enable Mockito Annotations
In JUnit 5, add this to your test class:
@ExtendWith(MockitoExtension.class)
public class MyServiceTest { ... }
✅ Spring Boot Test Annotations
Annotation | Purpose |
---|
@SpringBootTest | Loads full Spring context |
@WebMvcTest | Tests Spring MVC controllers only |
@DataJpaTest | Tests JPA repositories |
@MockBean | Replaces a Spring bean with a mock |
@Autowired | Injects dependencies |
🧪 Example
@ExtendWith(MockitoExtension.class)
class UserServiceTest {
@Mock
UserRepository userRepository;
@InjectMocks
UserService userService;
@BeforeEach
void setUp() {
// setup code
}
@Test
void testFindUser() {
when(userRepository.findById(1L)).thenReturn(Optional.of(new User("Alice")));
User result = userService.findUser(1L);
assertEquals("Alice", result.getName());
}
}