JUnit interview questions and answers: JUnit 5, Mockito and testing practice

· Updated · · 15 min read

Quick answer: a JUnit interview checks three things. Can you write a clear test with the JUnit 5 (Jupiter) API, can you isolate the code under test with mocks such as Mockito, and do you know what a test is worth: what it proves, what coverage misses and why a test becomes flaky. Below are 30 questions grouped by level, each with a short answer you can say aloud and a few lines of Java where code is clearer than words. The answers were checked against the JUnit User Guide, the Mockito documentation and the Spring Boot testing reference in November 2026.

On this page

How JUnit questions show up in interviews

JUnit rarely gets its own round. It comes up inside a Java interview ("how would you test this?"), in a live-coding task where you are asked to add a test after the code works, or in a code review exercise with a test that passes for the wrong reason. Interviewers listen for the same habits each time: one behaviour per test, a name that says what broke, mocks only at real boundaries, and no shared state between tests. The core Java side of the interview is in the Java interview questions and Spring Boot interview questions guides, test design in general is in the QA and SDET interview questions, and reviewing someone else's test is covered in the code review interview questions.

A note on versions: JUnit 6 is the current major release, but it keeps the Jupiter programming model, so the questions and annotations below are the ones interviewers still call "JUnit 5". JUnit 6 raised the minimum to Java 17 and gave all modules one version number (JUnit 6.0 release notes).

Junior JUnit interview questions

1. What is JUnit 5 made of?

JUnit 5 is three sub-projects. The JUnit Platform launches test engines on the JVM and is what IDEs and build tools talk to. JUnit Jupiter is the programming and extension model you write tests with (org.junit.jupiter.api). JUnit Vintage is an engine that runs old JUnit 3 and 4 tests on the platform; the user guide calls it deprecated and meant only for the migration period (JUnit overview).

2. What changed between JUnit 4 and JUnit 5?

The lifecycle annotations were renamed: @Before and @After became @BeforeEach and @AfterEach, @BeforeClass and @AfterClass became @BeforeAll and @AfterAll, @Ignore became @Disabled, @Category became @Tag. Runners and rules (@RunWith, @Rule) were replaced by one extension model, @ExtendWith and @RegisterExtension. @Test(expected = …) is gone in favour of assertThrows, and the optional failure message moved from the first argument of an assertion to the last (Migrating from JUnit 4). Test classes and methods also no longer need to be public; they only must not be private (Test classes and methods).

3. What does a basic JUnit 5 test look like?

A package-private class, a method annotated with @Test that returns void, and static imports from Assertions. Structure the body as arrange, act, assert so the reader sees the setup, the one action and the expected result.

import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Test;

class PriceCalculatorTest {

    @Test
    void appliesTenPercentDiscountForMembers() {
        var calculator = new PriceCalculator();          // arrange

        var total = calculator.total(100.0, true);       // act

        assertEquals(90.0, total, 0.001);                // assert (expected first)
    }
}

4. What are @BeforeEach, @AfterEach, @BeforeAll and @AfterAll?

@BeforeEach and @AfterEach run around every test method, so each test gets fresh setup. @BeforeAll and @AfterAll run once for the class, for expensive shared resources such as starting a container. By default they must be static, because JUnit creates a new test instance per method; they may be instance methods only when the class uses the per-class lifecycle (Annotations).

class RepositoryTest {

    static Database db;
    Repository repository;

    @BeforeAll
    static void startDatabase() { db = Database.startInMemory(); }

    @BeforeEach
    void freshRepository() { repository = new Repository(db); db.truncateAll(); }

    @AfterAll
    static void stopDatabase() { db.stop(); }
}

5. What do @DisplayName, @Disabled and @Tag do?

@DisplayName("…") gives a test a readable name in reports and IDEs, including spaces or emoji. @Disabled("reason") skips a test or a whole class; always write the reason and a ticket, or it stays disabled forever. @Tag("slow") labels tests so the build can include or exclude them, for example running only fast tests on every commit (Tagging and filtering).

6. Which JUnit assertions should you know?

assertEquals(expected, actual) (with a delta for doubles), assertNotEquals, assertTrue and assertFalse, assertNull and assertNotNull, assertSame for identity, assertArrayEquals and assertIterableEquals for contents, plus assertThrows, assertAll and assertTimeout. The message can be a Supplier<String>, so an expensive message is built only when the assertion fails (Assertions). Swapping expected and actual still fails correctly, but the failure message then reads backwards.

7. How do you test that a method throws an exception?

Use assertThrows. It fails if nothing is thrown or a different type is thrown, and it returns the exception, so you can also check its message or cause. That is stricter than JUnit 4's @Test(expected = …), which passed if any line of the test threw the exception. assertDoesNotThrow covers the opposite case.

@Test
void rejectsNegativeAmount() {
    var account = new Account();

    var ex = assertThrows(IllegalArgumentException.class,
            () -> account.withdraw(-5));

    assertEquals("amount must be positive", ex.getMessage());
}

8. What does assertAll do?

It runs every assertion in the group and reports all failures together, instead of stopping at the first one. Use it when several properties of one result belong together, such as the fields of a returned object, so one run shows the whole picture.

assertAll("address",
    () -> assertEquals("Kyiv", address.city()),
    () -> assertEquals("01001", address.postcode()),
    () -> assertNotNull(address.street()));

9. What is the difference between an assertion and an assumption?

A failed assertion fails the test. A failed assumption, such as assumeTrue(isCiServer()), aborts it: the test is reported as skipped, not failed, because its precondition does not hold in this environment (Assumptions). Use assumptions sparingly; a test that is always skipped on CI protects nothing.

10. What makes a good unit test?

It is fast, so people run it often. It is isolated: it does not depend on other tests, the order they run in, the clock, the network or a shared database. It is repeatable and gives the same result on every machine. It checks one behaviour, has a name that explains that behaviour and fails with a message that tells you what broke. Many teams summarise this as FIRST: fast, independent, repeatable, self-validating, timely. A good test also fails when the behaviour is wrong; a test that never fails is not protecting anything.

Mid-level JUnit interview questions

11. How do parameterized tests work in JUnit 5?

Replace @Test with @ParameterizedTest and add a source of arguments; JUnit runs the method once per argument set and reports each run separately. The simplest source is @ValueSource for a single literal argument. Parameterized tests live in the junit-jupiter-params artifact (Parameterized tests).

@ParameterizedTest
@ValueSource(strings = {"racecar", "radar", "level"})
void recognisesPalindromes(String word) {
    assertTrue(Strings.isPalindrome(word));
}

12. When would you use @CsvSource versus @MethodSource?

@CsvSource is for small tables of inputs and expected outputs written inline; quote a value with single quotes if it contains a comma, or use the textBlock attribute for a multi-line table. @MethodSource points to a factory method that returns a Stream of Arguments, for objects that are awkward to write as text. The factory method must be static unless the class uses the per-class lifecycle (Sources of arguments).

@ParameterizedTest
@CsvSource({
    "1, 1, 2",
    "2, 3, 5",
    "-1, 1, 0"
})
void adds(int a, int b, int expected) {
    assertEquals(expected, Math.addExact(a, b));
}

@ParameterizedTest
@MethodSource("invalidOrders")
void rejectsInvalidOrders(Order order) {
    assertThrows(ValidationException.class, () -> validator.check(order));
}

static Stream<Arguments> invalidOrders() {
    return Stream.of(
        Arguments.of(new Order(List.of())),            // no items
        Arguments.of(new Order(List.of(item(-1)))));   // negative quantity
}

13. Which other argument sources are useful?

@NullSource, @EmptySource and the combined @NullAndEmptySource add null and empty inputs, which are easy to forget. @EnumSource runs once per enum constant, optionally filtered. @CsvFileSource reads a CSV file from the classpath. Mentioning boundary values (empty, null, zero, maximum) shows you think about inputs, not only syntax.

14. What is @Nested for?

@Nested marks an inner class as a group of related tests, for example "when the stack is empty" and "after pushing an element". Each level can have its own @BeforeEach, which runs after the outer one, so setup reads like a story. Only non-static inner classes can be @Nested test classes (Nested tests).

class StackTest {
    Stack<String> stack;

    @BeforeEach
    void create() { stack = new Stack<>(); }

    @Nested
    class WhenEmpty {
        @Test
        void popThrows() { assertThrows(EmptyStackException.class, stack::pop); }
    }

    @Nested
    class AfterPush {
        @BeforeEach
        void push() { stack.push("a"); }

        @Test
        void peekReturnsElement() { assertEquals("a", stack.peek()); }
    }
}

15. What is the test instance lifecycle and when would you change it?

By default JUnit creates a new instance of the test class for every test method (PER_METHOD), so instance fields cannot leak state between tests. @TestInstance(Lifecycle.PER_CLASS) creates one instance for the whole class: @BeforeAll and @MethodSource methods may then be non-static, which is handy in Kotlin, but you must reset mutable fields yourself in @BeforeEach (Test instance lifecycle). Mention the trade-off: convenience against the risk of shared state.

16. What is the difference between assertTimeout, assertTimeoutPreemptively and @Timeout?

assertTimeout runs the code in the same thread and fails if it took too long, but only after it finishes. assertTimeoutPreemptively runs the code in a different thread and aborts it when time runs out; because of that separate thread, code that relies on ThreadLocal, such as Spring's test transactions, can behave differently (Assertions). The @Timeout annotation applies a limit to a whole test or lifecycle method, in seconds by default (Timeouts).

17. How does the JUnit 5 extension model work?

Extensions hook into the test lifecycle: callbacks before and after tests, parameter resolution, conditional execution, exception handling. You register them declaratively with @ExtendWith(SomeExtension.class), programmatically with a @RegisterExtension field when the extension needs configuration, or automatically through the service loader (Registering extensions). Built-in examples include @TempDir, which creates and cleans up a temporary directory for a test (Built-in extensions). Mockito's MockitoExtension and Spring's SpringExtension are the ones you will use most.

18. What is the difference between a mock, a stub and a spy?

A stub returns canned answers so the code under test can run. A mock is an object whose interactions you also verify. In Mockito, mock(Foo.class) creates an object whose methods do nothing and return defaults until you stub them. spy(realObject) wraps a real object: unstubbed calls run the real method. For spies, stub with doReturn(…).when(spy).method(), because when(spy.method()) calls the real method while stubbing (Mockito documentation). Needing a spy often means the class does too much.

19. How do you use Mockito with JUnit 5?

Add mockito-junit-jupiter, annotate the class with @ExtendWith(MockitoExtension.class), declare collaborators with @Mock and the class under test with @InjectMocks. The extension creates the mocks before each test and uses strict stubs by default: a stubbing that the test never uses fails with UnnecessaryStubbingException, which keeps tests honest (MockitoExtension). Constructor injection in production code makes this simpler, and you can always create the class under test with new yourself.

@ExtendWith(MockitoExtension.class)
class OrderServiceTest {

    @Mock PaymentGateway gateway;
    @Mock OrderRepository repository;
    @InjectMocks OrderService service;

    @Test
    void chargesCustomerAndSavesOrder() {
        when(gateway.charge("cust-1", 50)).thenReturn(Receipt.ok("r-1"));

        service.placeOrder("cust-1", 50);

        verify(repository).save(any(Order.class));
    }
}

20. How do when/thenReturn and verify work?

when(mock.call(args)).thenReturn(value) stubs a return value; thenThrow makes the call throw, which is how you test error paths. verify(mock).call(args) checks the call happened once; verify(mock, times(2)), never() and atLeastOnce() change the count. Verify the interactions that matter to the behaviour, such as "the email was sent". Verifying every call ties the test to the implementation, and the Mockito docs warn against calling verifyNoMoreInteractions() in every test (Mockito documentation).

when(inventory.reserve("sku-1", 2)).thenThrow(new OutOfStockException());

assertThrows(OutOfStockException.class, () -> service.placeOrder(order));
verify(gateway, never()).charge(anyString(), anyInt());

21. What is an ArgumentCaptor for?

It captures the argument passed to a mock so you can assert on it, useful when the code builds an object internally and passes it on. Mockito recommends using captors with verification, not with stubbing (ArgumentCaptor). If a simple eq(…) or argThat(…) matcher is enough, prefer that.

@Captor ArgumentCaptor<Email> email;

@Test
void sendsWelcomeEmail() {
    service.register("user-42");

    verify(mailer).send(email.capture());
    assertEquals("Welcome", email.getValue().subject());
}

22. Can Mockito mock final classes and static methods?

Yes, with the inline mock maker, which became Mockito's default in version 5.0. Static methods are mocked with mockStatic inside a try-with-resources block, so the mock is limited to the current thread and released afterwards (Mockito documentation). In an interview, add the design point: if you need to mock a static call, a small injected interface or a java.time.Clock is often the cleaner fix.

try (MockedStatic<UUID> uuid = mockStatic(UUID.class)) {
    uuid.when(UUID::randomUUID).thenReturn(FIXED_ID);
    assertEquals(FIXED_ID.toString(), service.newId());
}

23. How would you add AssertJ or Hamcrest?

JUnit's own assertions are deliberately small, and the user guide recommends third-party libraries such as AssertJ, Hamcrest or Truth when you need more (Assertions). AssertJ's fluent assertThat(list).hasSize(3).contains("a") gives readable chains and detailed failure messages for collections, exceptions and objects. Pick one style per codebase so tests read the same way.

Senior JUnit interview questions

24. What is the difference between unit and integration tests, and where do you draw the line?

A unit test checks one class or a small group of classes with its collaborators replaced, and runs in milliseconds. An integration test runs real pieces together: the database, the Spring context, HTTP serialisation, a message broker. Draw the line by risk: business rules in fast unit tests, the wiring and SQL in a smaller number of integration tests, and a few end-to-end checks of critical paths. Mocking the database in a test about a SQL query proves nothing; that query needs a real database, often in a container.

25. When do you use @SpringBootTest, @WebMvcTest or @DataJpaTest?

@SpringBootTest starts the full application context, for tests that need the real wiring. @WebMvcTest is a slice: it configures only the MVC layer (controllers, advice, converters, filters), not regular @Component beans, and gives you MockMvc. @DataJpaTest configures JPA repositories and, by default, makes each test transactional and rolls it back at the end (Spring Boot testing). Collaborators of a slice are replaced with @MockitoBean from Spring Framework (@MockitoBean); the older @MockBean was deprecated for removal in Spring Boot 3.4 (MockBean Javadoc).

@WebMvcTest(OrderController.class)
class OrderControllerTest {

    @Autowired MockMvc mvc;
    @MockitoBean OrderService service;

    @Test
    void returns404ForUnknownOrder() throws Exception {
        when(service.find("x")).thenReturn(Optional.empty());

        mvc.perform(get("/orders/x")).andExpect(status().isNotFound());
    }
}

26. How do you keep tests isolated from each other?

No shared mutable static state, no reliance on execution order, and each test creates the data it needs. JUnit's default method order is deterministic but intentionally nonobvious, so a suite that passes only in one order is already broken; @TestMethodOrder with @Order exists for the rare case that really needs order (Test execution order). Use @TempDir for files, transactions that roll back for the database, and a fixed Clock for time. Parallel execution is opt-in through junit.jupiter.execution.parallel.enabled (Parallel execution), and turning it on is a quick way to expose hidden shared state.

27. What does code coverage tell you, and what does it miss?

A tool such as JaCoCo reports which instructions, branches and lines ran during the tests (JaCoCo coverage counters). It is useful for finding code no test touches. It does not show whether anything was asserted: a test that calls a method and checks nothing still raises coverage. Use a coverage floor as a guard against untested new code, not as a target to chase; mutation testing tools such as PIT go further by changing the code and checking that some test fails.

28. What is TDD and when does it help?

Test-driven development is a short loop: write a failing test for the next small behaviour, write the simplest code that passes, then refactor with the test as a safety net, often called red, green, refactor (Martin Fowler on TDD). It helps most with logic that has clear rules and edge cases, and it pushes you towards small, injectable units. Be honest about when you use it; interviewers value a reasoned answer over a claim that you always do TDD.

29. How do you find and fix a flaky test?

A flaky test passes and fails on the same code. Common causes are time (LocalDate.now(), time zones), fixed Thread.sleep waits for asynchronous work, shared state or order between tests, random data without a seed and real network calls. Reproduce it first: run it many times, for example with @RepeatedTest (Repeated tests), alone and in parallel. Then remove the cause: inject a Clock, wait for a condition instead of sleeping, isolate the data. Quarantine it with a ticket if it blocks the team, but do not make automatic reruns the permanent fix.

30. How do you name and structure tests?

The name should state the behaviour and the condition, so a failure explains itself: withdraw_throwsWhenBalanceIsInsufficient or a @DisplayName such as "throws when balance is insufficient". Inside, keep arrange, act, assert (or given, when, then) visually separate, keep one reason to fail per test, and move repeated setup into helpers or builders rather than copying it. A reviewer should understand the test without opening the production code.

How to practise these answers

  • Write the snippets, then break them. Change the expected value, remove a stub, drop the static from a @BeforeAll method and read the real error. That is what makes the answer stick.
  • Test a small class end to end. Take a service with two collaborators and write the unit test with Mockito, then a @WebMvcTest or @DataJpaTest for the layer around it. Be ready to explain why each test sits where it does.
  • Expect testing inside a coding round. "Now add a test" is a common follow-up in a live coding interview, and the technical interview preparation plan shows where it fits.
  • Prepare one story. "Tell me about a bug a test caught, or missed" is a behavioural question; the STAR method keeps the answer short.

Before a live assessment, ask the recruiter which Java version, test libraries and documentation are allowed.

Where Interview Copilot fits

We make Interview Copilot, a desktop app that listens to the call and puts a suggested answer on your screen, so this paragraph is about our own product. In a knowledge round like this one it can bring up the concept behind a question, such as the difference between a mock and a spy, while you are answering. It does not replace knowing the material, and it belongs only in interviews where your own tools are allowed: if you are not sure what the rules are, ask the recruiter before the round starts. A free plan exists if you want to try it while you practise.

Sources

Documentation was read on 19 November 2026, against JUnit 6.1 and Mockito 5. Annotation names are the same in JUnit 5 and JUnit 6; check the versions your project uses.

FAQ

What are the most common JUnit interview questions?

The difference between JUnit 4 and JUnit 5, the lifecycle annotations @BeforeEach and @BeforeAll, assertEquals and assertThrows, parameterized tests with @CsvSource or @MethodSource, mocking with Mockito, the difference between unit and integration tests, code coverage and flaky tests.

What is the difference between JUnit 4 and JUnit 5?

JUnit 5 is split into the Platform, Jupiter and Vintage. Lifecycle annotations were renamed (@Before to @BeforeEach, @BeforeClass to @BeforeAll, @Ignore to @Disabled), runners and rules were replaced by @ExtendWith, @Test(expected) by assertThrows, and test classes no longer need to be public.

Why must @BeforeAll methods be static?

JUnit creates a new test instance for every test method by default, so a method that runs once for the whole class cannot belong to one instance. With @TestInstance(Lifecycle.PER_CLASS) there is one instance per class and @BeforeAll may be an instance method.

What is the difference between mock and spy in Mockito?

A mock replaces the whole object: methods do nothing and return defaults until stubbed. A spy wraps a real object and calls real methods unless stubbed. Stub spies with doReturn(...).when(spy) so the real method is not called during stubbing.

Is JUnit 5 still relevant now that JUnit 6 exists?

Yes. JUnit 6 keeps the Jupiter API, so the annotations, assertions and extension model are the same. The main changes are a Java 17 minimum and one version number for all modules. Interviewers still usually say JUnit 5.

How much code coverage is enough?

There is no universal number. Coverage shows which code ran, not whether it was checked, so use a floor to catch untested new code and judge tests by whether they fail when behaviour breaks. Mutation testing gives a stronger signal.

Related articles

More guides

Related articles

Read next

Interview Copilot is a desktop app

It's a desktop app for macOS, Windows and Linux — a phone cannot capture the interviewer's audio or hide a window from screen share. Open this page on your computer to install it.

And during the interview this phone can be your screen: scan the QR code in the laptop app and the answers appear right here. How phone mode works →