JUnit 5 introduced an extension model. What is its main purpose?
Think about how you can customize or extend test execution behavior in JUnit.
The extension model in JUnit 5 lets you add custom behavior such as before/after callbacks, parameter injection, and conditional test execution. It does not replace assertions or generate data automatically.
Given the following JUnit 5 extension and test class, what will be printed when the test runs?
import org.junit.jupiter.api.extension.*; public class SimpleExtension implements BeforeEachCallback { @Override public void beforeEach(ExtensionContext context) { System.out.println("Before each test"); } } import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; @ExtendWith(SimpleExtension.class) public class MyTest { @Test void testMethod() { System.out.println("Test method running"); } }
Remember that BeforeEachCallback runs before each test method.
The extension's beforeEach method runs before the test method, so "Before each test" prints first, then the test method prints "Test method running".
You want to verify that a JUnit extension's beforeAll method was called exactly once before all tests. Which assertion correctly checks this?
Think about how to check the exact number of times a method was called.
To verify the method was called exactly once, assert that the call count equals 1. Other options check for wrong conditions or null.
Consider this JUnit 5 extension class:
public class MyExtension implements BeforeEachCallback {
public void beforeAll(ExtensionContext context) {
System.out.println("Before all tests");
}
@Override
public void beforeEach(ExtensionContext context) {
System.out.println("Before each test");
}
}Why is "Before all tests" never printed?
Check which methods JUnit calls automatically in extensions.
JUnit calls lifecycle methods only if they override interface methods or are annotated properly. The beforeAll method here is just a normal method and not called automatically.
You want to skip a test if a certain environment variable is not set. Which JUnit 5 extension interface should you implement to conditionally disable tests?
Think about how to enable or disable tests before they run.
The ExecutionCondition interface allows you to decide if a test should run or be skipped based on conditions like environment variables.