JUnit interview questions and answers for Java developers and SDETs

JUnit interview questions check that you can write focused, readable Java tests and explain how the framework runs them: the Jupiter annotations and life cycle, assertions such as assertThrows and assertAll, parameterized tests, extensions, and mocking collaborators with Mockito. Expect to write a test for a small class, migrate a JUnit 4 test, and discuss flaky tests and what belongs in unit versus integration tests. Good answers show judgment about what to test, not only syntax.

By Published 7 min read

How JUnit is tested in interviews

JUnit appears in Java developer, SDET and test automation interviews, and in code reviews where the interviewer asks how you would prove a change works. Some loops ask you to add tests to the code you just wrote in a live round. Others give you a weak or flaky test and ask what is wrong. Automation roles add the build side: how tests are selected, tagged and run in CI. For JavaScript testing the equivalent page is Jest interview questions.

  1. Concept questionsAnnotations, life cycle, assertions and the differences between JUnit 4 and the Jupiter API.
  2. Write a testUnit tests for a small class, often including an exception path and several inputs.
  3. MockingIsolate a service from its repository or HTTP client with Mockito, and explain what you verified and why.
  4. Test designFlaky tests, slow suites, the test pyramid and what you would not unit test.

JUnit fundamentals questions

First-round questions
QuestionWhat it testsWhat a strong answer shows
What are Platform, Jupiter and Vintage?ArchitectureThe Platform launches test engines and integrates with IDEs and build tools. Jupiter is the programming model and engine for modern tests. Vintage is an engine that runs old JUnit 3 and 4 tests on the Platform.
Which life cycle annotations exist?Life cycle@BeforeEach and @AfterEach around every test, @BeforeAll and @AfterAll once per class. In JUnit 4 these were @Before, @After, @BeforeClass and @AfterClass.
Why must @BeforeAll methods usually be static?InstancesJupiter creates a new test class instance per test method by default, so a once-per-class method cannot belong to one instance. With @TestInstance(Lifecycle.PER_CLASS) it can be non-static.
Why a new instance per test method?IsolationFields set by one test cannot leak into another, which keeps tests independent and order-free.
In what order do test methods run?OrderingDeterministic but deliberately not obvious. Tests should not depend on order; if you truly need it, @TestMethodOrder with @Order makes it explicit.
How do you skip a test?Control@Disabled with a reason, or conditional annotations such as @EnabledOnOs or @EnabledIfEnvironmentVariable. An assumption skips at runtime when a precondition is not met.
Assertion versus assumption?SemanticsA failed assertion fails the test. A failed assumption (assumeTrue) aborts it as skipped, for tests that only make sense in some environments.
What does @DisplayName do?ReadabilityGives the test a readable name in reports, such as "rejects an expired coupon", instead of a method name.
Do test classes and methods need to be public in Jupiter?SyntaxNo. Package-private is enough and is the common style. JUnit 4 required public.
Where is the message argument in Jupiter assertions?Migration trapLast, for example assertEquals(expected, actual, "message"). JUnit 4 put it first, so mechanical migrations can swap meanings.
First-round questions. Scroll sideways on a small screen.

Writing tests: assertions and parameterized tests

import static org.junit.jupiter.api.Assertions.*;

import org.junit.jupiter.api.*;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;

class DiscountCalculatorTest {

    private DiscountCalculator calc;

    @BeforeEach
    void setUp() {
        calc = new DiscountCalculator();
    }

    @ParameterizedTest(name = "{0} cents with tier {1} costs {2}")
    @CsvSource({
        "10000, BRONZE, 10000",
        "10000, SILVER,  9500",
        "10000, GOLD,    9000",
        "0,     GOLD,       0"
    })
    void appliesTierDiscount(long priceMinor, Tier tier, long expected) {
        assertEquals(expected, calc.finalPrice(priceMinor, tier));
    }

    @Test
    @DisplayName("rejects a negative price with a clear message")
    void rejectsNegativePrice() {
        var ex = assertThrows(IllegalArgumentException.class,
                () -> calc.finalPrice(-1, Tier.GOLD));
        assertTrue(ex.getMessage().contains("price"));
    }

    @Test
    void breakdownIsConsistent() {
        var b = calc.breakdown(10000, Tier.SILVER);
        assertAll(
            () -> assertEquals(10000, b.original()),
            () -> assertEquals(500, b.discount()),
            () -> assertEquals(9500, b.total())
        );
    }
}
Tests for a small discount calculator. Not executed here; it needs the JUnit Jupiter and params artifacts on the classpath.
  • Why assertThrows instead of a try/catch or `expected=`? It pins the exception to one lambda, not the whole test, and returns the exception so you can check its message or fields. JUnit 4's expected passed if any line threw.
  • What does assertAll add? It runs every grouped assertion and reports all failures together, so one run shows the whole picture instead of stopping at the first mismatch.
  • Which sources can feed a parameterized test? @ValueSource for single literals, @CsvSource or @CsvFileSource for rows, @MethodSource for objects built in code, @EnumSource for enum constants, and @NullAndEmptySource for edge inputs.
  • How is CSV text turned into an enum or a long? Implicit argument conversion handles primitives, enums by name, dates and more. For custom types, write an ArgumentConverter or use an aggregator.
  • assertTimeout or assertTimeoutPreemptively? The first runs the code in the same thread and reports if it was too slow after it finishes. The preemptive one aborts it from another thread, which can break code that relies on thread-local state such as transactions.
  • What are @Nested tests for? Grouping tests by scenario in inner classes, for example "when the cart is empty" and "when a coupon is applied", each with its own setup. Reports read like a specification.
  • What is a @TestFactory? A method that returns dynamic tests built at runtime, useful when cases come from data you only know when the test runs.
  • How do you test code that writes files? Inject a temporary directory with @TempDir; JUnit creates it before the test and deletes it afterwards.
  • Should you use AssertJ or Hamcrest? Either can make failures more readable, especially for collections and objects. AssertJ's fluent style is common in Spring projects; built-in assertions are fine for simple values.

Extensions, mocking and integration tests

Intermediate questions
QuestionWhat it testsWhat a strong answer shows
What replaced JUnit 4 runners and rules?Extension modelExtensions, registered with @ExtendWith or @RegisterExtension. They hook into the life cycle (before and after callbacks, parameter resolution, exception handling) and several can be combined, unlike a single runner.
How do you use Mockito with Jupiter?Mocking@ExtendWith(MockitoExtension.class), then @Mock for collaborators and @InjectMocks for the class under test. Stub with when(...).thenReturn(...) and check interactions with verify.
What is UnnecessaryStubbingException?Strict stubsThe Mockito extension uses strict stubbing, so a stub the test never uses fails the test. It catches copy-pasted setup that no longer matters.
When do you use an ArgumentCaptor?VerificationWhen you need to inspect an object your code built and passed to a collaborator, for example the email a service sent to a gateway.
What should you not mock?DesignValue objects, simple data structures and the class under test. Mocking types you do not own, like an HTTP client library, often leads to brittle tests; wrap them in your own interface.
Unit test or integration test for a repository query?Test levelsIntegration test against the real database engine, for example in a container with Testcontainers, because the query's correctness depends on the database.
What are Spring Boot test slices?SpringAnnotations such as @WebMvcTest and @DataJpaTest that load only part of the context, which is faster than @SpringBootTest. Collaborators outside the slice are replaced with mocks.
How do you separate unit and integration tests in the build?Build toolingMaven Surefire for unit tests and Failsafe for integration tests, or tags with @Tag and filtered tasks in Gradle, so fast tests run on every commit.
Intermediate questions. Scroll sideways on a small screen.

Senior and scenario questions

  • A test fails once in twenty runs in CI. How do you approach it? Reproduce by running it in a loop, then look at the usual causes: shared static state, test order, time and time zones, random data without a seed, async code with sleeps, and parallel tests touching the same resource. Quarantine it with a ticket rather than deleting it or retrying forever.
  • How do you test code that depends on the current time? Inject a java.time Clock and use Clock.fixed in tests. Calling LocalDate.now() directly makes tests change behavior at midnight or month end.
  • Can JUnit run tests in parallel? Yes, Jupiter supports parallel execution once enabled through configuration parameters such as junit-platform.properties. Tests must be isolated first; shared fixtures need @ResourceLock or should stay sequential.
  • Is high line coverage a good target? It is a weak signal on its own. Coverage shows what ran, not what was checked. Mutation testing tools such as PIT reveal tests that execute code without asserting anything useful.
  • The suite takes twenty minutes. How do you speed it up? Measure which tests are slow, move logic tests away from full Spring contexts, reuse cached contexts by keeping configuration consistent, run in parallel and keep heavy integration tests in a separate stage.
  • How do you migrate a large JUnit 4 suite? Add the Jupiter engine alongside Vintage so both run, migrate package by package (imports, annotations, rules to extensions, expected to assertThrows), and remove Vintage at the end.
  • What makes a good unit test name and structure? One behavior per test, a name that states the expectation, and arrange, act, assert separated clearly. A failing test should tell you what broke without opening the code.

Fictional example

Answering "Write tests for this service that calls a payment gateway"
Interviewer
CheckoutService charges the card through a PaymentGateway and saves the order. How would you test it?
Candidate
I would write unit tests with Mockito: the gateway and order repository are mocks, and the service is the real class. One test for the happy path that verifies the charge amount with an ArgumentCaptor and that the order is saved as paid. One for a declined card, where the gateway returns a decline, asserting the order is saved as failed and no confirmation is sent. One where the gateway throws a timeout, asserting we do not mark the order paid and that the exception is translated for the caller. I would not mock the order or money types, they are plain values. Separately, I would add one integration test for the real repository in a container, and a contract test for the gateway client, since mocks cannot tell me the real API changed.

JUnit practice plan

  • Day 1: write tests for a small class with a parameterized test, an exception test with assertThrows and a grouped assertAll.
  • Day 2: add Mockito to test a service with two collaborators, then delete one stub and read the strict-stubbing failure.
  • Day 3: convert three JUnit 4 tests with rules and expected to Jupiter and explain each change.
  • Day 4: write a deliberately flaky test using the system clock and fix it with an injected Clock.
  • Day 5: rehearse the scenario answers and the example above, keeping each under two minutes.

Neighboring topics: Java Collections interview questions for the structures your tests often assert on, automation testing interview questions for framework and CI design, and JMeter interview questions for the load-testing side of quality work.

A test-writing round is judged on which cases you choose before any code appears. Natively, an AI interview assistant for Mac and Windows, transcribes your practice round on the computer, so you can review whether you named the decline and timeout paths before starting to type. In practice it can read a class from a screenshot and suggest test cases, and with Pro or the free trial it reflects the résumé and job description you add. Your transcripts and notes stay available afterwards.

Questions people ask

What JUnit questions are asked in interviews?

JUnit 5 architecture, life cycle annotations, assertions such as assertThrows and assertAll, assumptions, parameterized and nested tests, extensions versus JUnit 4 runners, Mockito usage, and how to fix flaky tests.

What is the difference between JUnit 4 and JUnit 5?

JUnit 5 splits into Platform, Jupiter and Vintage, renames life cycle annotations to @BeforeEach and @BeforeAll, replaces runners and rules with extensions, and adds assertThrows, assertAll, nested and parameterized tests.

Why are @BeforeAll methods static in JUnit 5?

Jupiter creates a new test instance for each test method by default, so a once-per-class method cannot belong to one instance, unless the class uses @TestInstance(Lifecycle.PER_CLASS).

How do you use Mockito with JUnit 5?

Add @ExtendWith(MockitoExtension.class), declare collaborators with @Mock and the class under test with @InjectMocks, stub with when and thenReturn, and verify interactions.

Where to go next

Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.

Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.

Keep reading

Put it on your own machine.

A live-conversation assistant that runs locally. Your conversations stay on your machine.

macOS 12+ · Windows 10/11

© 2026 Natively AI Private Limited

Source-available under the Natively Personal Use Source License v1.0 · IP geolocation by DB-IP