Skip to content
Tutorials Center
My learning

Topics

Lesson 28 of 29 ยท Practice and review

JUnit and TestNG Interview Questions

40 JUnit and TestNG interview questions with short, accurate answers and small code examples: lifecycle, assertions, parameterized tests, groups, listeners and design.

Interviewers rarely want a list of annotations. They want to hear that you know why a feature exists, what goes wrong when it is misused, and how you would choose between two options. The forty questions below are grouped by topic, and each answer is short enough to say out loud. Where a code sample helps, it is a few lines long. Most code is read-only; two blocks are runnable checks that prove a claim instead of asking you to trust it.

Five topics, 40 questions

Basics Questions 1 to 8.
JUnit core Questions 9 to 20.
JUnit advanced Questions 21 to 26.
1 / 2

Basics

1. What is a unit test, and how is it different from an integration test? A unit test checks one small piece of behavior in isolation, usually without a database, network or file system, and runs in milliseconds. An integration test checks that several real parts work together (a service with its database, say). A healthy suite has many unit tests and fewer, slower integration tests. See the testing landscape.

2. What is the difference between JUnit and TestNG in one sentence? JUnit is the most widely used Java testing library, built around small, independent tests; TestNG started as a more feature-rich alternative with groups, dependencies, data providers and XML suites built in, aimed at larger integration and end-to-end suites. Both can drive the same code.

3. What are the parts of JUnit 6? The Platform (launcher, discovery and reporting API that build tools and IDEs use), the Jupiter engine and API (the annotations and assertions you write against), and the Vintage engine that runs old JUnit 3 and 4 tests on the Platform. Other engines, including one for TestNG, plug into the same Platform.

4. When does a JUnit test pass, and what are the other results? It passes when the method returns without throwing. It fails when an assertion throws AssertionFailedError, and it errors when any other exception escapes (the report usually lumps both as failed). It is skipped when disabled or filtered, and aborted when an assumption is not met.

5. What is arrange-act-assert? A layout for each test: build the inputs and objects (arrange), call one behavior (act), check the outcome (assert). It keeps tests readable and makes it obvious when a test checks too much.

6. Why can Jupiter test methods be package-private? Jupiter finds them by reflection and does not need public, unlike JUnit 4. Test methods must not be private or static, and must return void. Package-private keeps the test API quiet.

7. How do Maven's Surefire plugin and the test class name relate? By default Surefire only runs classes whose names match patterns such as *Test, Test* and *Tests. A class named OrderChecks is silently ignored. Integration tests are often named *IT and run by the Failsafe plugin instead (Maven and Gradle).

8. What is a good test name? One that states the behavior and the condition, such as rejectsPasswordsWithoutDigits. The failing line in a report should tell you what broke before you open the code.

JUnit core

9. What is the difference between @BeforeEach and @BeforeAll? @BeforeEach runs before every test method, @BeforeAll once before all tests in the class. @BeforeAll methods must be static, unless the class uses @TestInstance(Lifecycle.PER_CLASS).

10. How many instances of a test class does JUnit create? By default one per test method, so fields set by one test never leak into the next. @TestInstance(PER_CLASS) switches to one instance for the whole class, which is why @BeforeAll may then be non-static. TestNG, by contrast, uses one instance per class.

11. How do you temporarily skip a test? @Disabled("reason"). Always give a reason, and track disabled tests, because they quietly rot. Conditions such as @EnabledOnOs skip a test only in some environments (Conditions and Tags).

12. What are @DisplayName and @Nested for? @DisplayName gives a test or class a human-readable report name. @Nested places a non-static inner class inside a test class so a group of tests can share a situation and set-up; outer @BeforeEach methods run before inner ones.

13. What is @Tag used for? Labelling tests (fast, slow, integration) so the build can include or exclude them. Tags are the Jupiter counterpart of TestNG groups, with simpler expression rules.

14. What does @RepeatedTest(5) do? Runs the same test five times, each a separate result with its own index. Useful when hunting a rare failure, not as a way of hiding flakiness.

15. How does @Timeout behave? It fails the test if it takes longer than the limit (the default unit is seconds). @Timeout runs the test on the same thread and checks afterward, unless you configure the thread mode. assertTimeoutPreemptively runs the code on another thread and aborts it, with the caveat that thread-bound things such as transactions may not follow.

16. What does assertAll do? It runs several assertions and reports all that fail, instead of stopping at the first. Use it for independent facts about one result, such as the fields of a parsed object.

17. How do you test that code throws? assertThrows(IllegalStateException.class, () -> account.withdraw(80)). It returns the exception so you can check the message. It replaces JUnit 4's @Test(expected = ...), which could not check messages and passed if any line in the method threw.

18. How do you compare doubles? With a delta: assertEquals(0.3, 0.1 + 0.2, 1e-9). Binary floating point cannot represent most decimals exactly, so exact equality is a bug waiting to happen.

19. What is an assumption? assumeTrue(condition) aborts the test (not fails it) when the condition is false, for example "only meaningful on CI". Use it when the test is not applicable, not to hide a failure.

20. What does @TempDir give you? A fresh temporary directory (as a Path or File parameter or field) that JUnit deletes after the test, so file-based tests leave no mess.

The first runnable check proves two of those claims at once, the per-method instances (question 10) and the order of the lifecycle callbacks (question 9). The helper at the bottom stands in for your build tool.

Java Lifecycle order and instances

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Both tests report counter=1, because each ran on a fresh object: the run created two distinct instances, one per test method. @BeforeAll and @AfterAll appear once, wrapping the rest.

JUnit advanced

21. How do parameterized tests work? @ParameterizedTest runs one method once per argument set from a source: @ValueSource (single values), @CsvSource (rows), @MethodSource (a factory method), @EnumSource, @NullSource and @ArgumentsSource. Each invocation is reported separately (Parameterized and Dynamic Tests).

22. What must a @MethodSource method look like? By default a static method with no parameters returning a Stream, Iterable or array of arguments (Arguments.of(...)), unless the class uses PER_CLASS.

23. When would you use @TestFactory over @ParameterizedTest? When the set of tests is computed at run time in ordinary Java (read from files, generated from a model). A @TestFactory returns DynamicTest objects; lifecycle callbacks run around the factory method, not around each dynamic test.

24. What replaced @RunWith and @Rule? The extension model. One mechanism, @ExtendWith, covers what runners and rules did in JUnit 4, through callbacks such as BeforeEachCallback and ParameterResolver (Writing JUnit Extensions).

25. @ExtendWith or @RegisterExtension? @ExtendWith registers an extension declaratively by class. @RegisterExtension registers an instance held in a field, which lets you configure it in code (a mock server on a chosen port, a fake clock).

26. How do you use Mockito with JUnit? Add @ExtendWith(MockitoExtension.class), then annotate fields with @Mock and @InjectMocks. The extension uses strict stubbing by default, so an unused stub fails the test with UnnecessaryStubbingException (Mocks and Spies).

TestNG

27. What is the order of TestNG configuration methods? @BeforeSuite, @BeforeTest, @BeforeClass, @BeforeMethod, the test, then the matching After methods in reverse: @AfterMethod, @AfterClass, @AfterTest, @AfterSuite. @BeforeGroups and @AfterGroups wrap a group (Lifecycle).

28. What is testng.xml? The suite description: which classes, packages and groups to run, parameters, listeners, and parallelism. A <suite> contains <test> elements, which contain <classes>. Note that an XML <test> is a set of classes, not a single @Test method.

29. How do groups work? Tag methods with @Test(groups = {"smoke"}), then include or exclude groups in testng.xml or from the build. Groups can contain other groups ("meta-groups"), and exclusion wins over inclusion (Assertions and Groups).

30. What does dependsOnMethods do, and what is the catch? The dependent test runs only if the named methods passed; otherwise it is skipped. The catch is that tests become coupled, one failure hides many results, and parallel runs get harder. Prefer independent tests with their own set-up (Dependencies).

31. What is a @DataProvider? A method returning Object[][] (or an iterator) that feeds a test method with several argument sets. It can run in parallel with parallel = true. @Parameters instead injects named values from testng.xml, one set per <test> (Data Providers).

32. How do TestNG assertions differ from JUnit's? The argument order: TestNG's assertEquals(actual, expected) versus JUnit's assertEquals(expected, actual). The messages swap meaning if you mix them up.

33. What is SoftAssert? A TestNG helper that records failures and throws them all at assertAll(). If you forget assertAll(), nothing ever fails.

34. How do you run TestNG tests in parallel? Set parallel="methods", "classes" or "tests" with thread-count on the <suite>; use @Test(threadPoolSize = n, invocationCount = m) for one method; use parallel = true on a data provider. Tests then must not share mutable state.

35. What are listeners and retry analyzers? ITestListener is called as tests start, pass, fail or skip (logging, screenshots, notifications). IRetryAnalyzer decides whether a failed test should run again. Retries hide flakiness, so log each one and use them sparingly (Listeners, Retry and Parallel Execution).

36. How does priority order tests, and should you rely on it? Lower numbers run first (the default is 0); equal priorities fall back to an unspecified, deterministic order. It is fine to speed up feedback; it is not fine to make tests depend on each other's side effects.

The second runnable check makes question 32 concrete. It uses a stand-in with the two argument orders, since TestNG itself cannot run here, and prints the message each convention produces when the same bug appears.

JS Argument order changes the message

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The swapped lines still fail, but they claim the wrong thing: the first reader of that message hunts for a bug in the correct value. That is the whole risk of mixing the two conventions in one codebase.

Design and practice

37. What is the difference between a stub, a mock, a spy and a fake? A stub returns canned answers; a mock also verifies how it was called; a spy wraps a real object and records calls; a fake is a working simplified implementation (an in-memory repository). Prefer fakes and stubs, and mock only the interactions that matter.

38. What makes a test flaky, and how do you fix it? Shared state, order dependence, real time, randomness, sleeps and real networks. Fixes: isolate state per test, inject a Clock and a seeded random generator, wait for conditions instead of sleeping, and fake the network (Flaky Tests).

39. Does 100 percent coverage mean good tests? No. Coverage shows which lines ran, not whether anything was checked. A test with no assertions raises coverage and proves nothing. Mutation testing (such as PIT) is a stricter check, because it asks whether the tests notice small code changes (Coverage and CI).

40. How would you choose between JUnit and TestNG for a new project? Default to JUnit: the broadest ecosystem, IDE and framework support, and the Jupiter extension model. Choose TestNG when you need its built-in suite features (XML suites, groups with dependencies, data-provider parallelism) or you inherit a TestNG codebase. Do not mix them in one module without a reason (JUnit vs TestNG).

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which statement about the default JUnit Jupiter lifecycle is correct?

    PER_METHOD is the default, which isolates instance fields between tests. PER_CLASS must be requested with @TestInstance.
  2. 2. A test is aborted rather than failed when...

    A failed assumption signals that the test does not apply here, so JUnit reports it as aborted, not failed.
  3. 3. In TestNG, what is the correct argument order for assertEquals?

    TestNG takes the actual value first. Swapping them only changes the failure message, but it misleads whoever reads it.
  4. 4. Why is heavy use of dependsOnMethods discouraged?

    Dependent tests hide results behind one failure and cannot be run alone or reordered freely.
  5. 5. What does 100 percent line coverage prove?

    Coverage measures execution. Assertions are what check behavior, and mutation testing is one way to measure how well they do.

Summary

  • Know the structure: JUnit Platform, Jupiter and Vintage; TestNG as a separate library with its own suites.
  • Explain results precisely: pass, fail, error, skipped, aborted.
  • Remember the defaults: new instance per JUnit test method, @BeforeAll static, TestNG one instance per class.
  • Parameterized, dynamic, nested and extension features answer "how do I avoid duplication and share set-up" in JUnit; groups, data providers and suites answer it in TestNG.
  • TestNG's assertEquals(actual, expected) is the reverse of JUnit's.
  • Good answers always include a trade-off: dependencies, retries, mocks and coverage all have a cost.

Next: JUnit and TestNG Cheat Sheet, the whole track on a few pages.