JUnit Interview Guide
1. What is JUnit?
JUnit is a unit testing framework for Java programming language. It helps developers write and run
repeatable tests.
- JUnit 4 and JUnit 5 (also called Jupiter) are the most commonly used versions.
- It is used to test individual units of source code (methods/classes).
2. JUnit 5 Architecture
JUnit 5 = JUnit Platform + JUnit Jupiter + JUnit Vintage
- **JUnit Platform**: Foundation for launching testing frameworks.
- **JUnit Jupiter**: New programming model for writing tests in JUnit 5.
- **JUnit Vintage**: Supports running older JUnit 3 & 4 tests.
3. Common JUnit 5 Annotations
- @Test - Marks a method as a test
- @BeforeEach - Runs before each test method
- @AfterEach - Runs after each test method
- @BeforeAll - Runs once before all tests (static method)
- @AfterAll - Runs once after all tests (static method)
- @Disabled - Disables a test class or method
- @DisplayName - Sets custom name for test method
JUnit Interview Guide
4. Assertions
- assertEquals(expected, actual)
- assertTrue(condition)
- assertFalse(condition)
- assertThrows(Exception.class, () -> { /* code */ })
- assertAll(() -> assertEquals(...), () -> assertTrue(...))
- assertTimeout(Duration.ofSeconds(1), () -> { /* code */ })
5. Parameterized Tests
Use @ParameterizedTest with @ValueSource, @CsvSource, etc.
Example:
@ParameterizedTest
@ValueSource(strings = { "racecar", "radar", "level" })
void testPalindrome(String word) {
assertTrue(isPalindrome(word));
6. Mockito with JUnit
Mockito is used to mock dependencies and verify interactions.
Basic Example:
@Mock
private MyService service;
JUnit Interview Guide
@InjectMocks
private MyController controller;
@BeforeEach
void setup() {
MockitoAnnotations.openMocks(this);
@Test
void testServiceCall() {
when(service.getData()).thenReturn("Mocked");
assertEquals("Mocked", controller.fetchData());
7. JUnit 4 vs JUnit 5
| Feature | JUnit 4 | JUnit 5 |
|-----------------|----------------|------------------|
| Annotations | org.junit.* | org.junit.jupiter.* |
| Test Runner | @RunWith | Extension Model |
| Parameter Tests | @RunWith | @ParameterizedTest |
| Parallel Tests | Limited | Supported |
| Lambda Support | No | Yes |
8. Best Practices
JUnit Interview Guide
- Write tests for all critical business logic.
- Keep tests independent and repeatable.
- Use meaningful method names (testMethodName_shouldDoSomething).
- Prefer assertions over logs.
- Avoid hardcoding - use constants or factories.
- Use test coverage tools (e.g., JaCoCo).
9. Interview Questions
- What's the difference between JUnit 4 and JUnit 5?
- How do you test exceptions in JUnit?
- What is the use of @BeforeEach vs @BeforeAll?
- What are mocks and spies?
- What are the benefits of unit testing?
- How do you run parameterized tests in JUnit 5?
- How can you test private methods?
- How do you integrate JUnit with Maven or Gradle?