JUnit 5 Basics Java | Fresher Interview
Fast recall
Quick revision
Core answer
@Test that arranges a scenario, calls the code, and verifies observable behavior with an assertion.Interview-ready guide
Interview answer
JUnit 5 is built around the JUnit Platform, which discovers and launches test engines, and JUnit Jupiter, which supplies the @Test annotation, assertions, lifecycle callbacks, and extension model. The optional Vintage engine lets the Platform execute JUnit 3 and 4 tests during migration. A basic Jupiter test uses a non-private void method annotated with org.junit.jupiter.api.Test, arranges the scenario, calls the behavior, and asserts the result. Package-private classes and methods are allowed. If a class imports org.junit.Test, it is a JUnit 4 test and needs the Vintage engine; it is not a Jupiter test merely because the build uses the JUnit Platform.
JUnit 5 Basics Java | Fresher Interview
Direct Answer
JUnit 5 is a widely used Java testing generation built around the JUnit Platform launcher and test-engine API, the JUnit Jupiter programming and extension model, and the optional Vintage engine for JUnit 3/4 tests. A basic Jupiter test is a non-private method annotated with @Test that arranges a scenario, calls the code, and verifies observable behavior with an assertion.
Code Example
import org.junit.jupiter.api.Test; // Jupiter API
import static org.junit.jupiter.api.Assertions.*; // static assertions
class CalculatorTest { // no 'public' needed in JUnit 5
@Test
void shouldAddTwoNumbers() {
// Arrange
var calc = new Calculator();
// Act
int result = calc.add(2, 3);
// Assert
assertEquals(5, result, "2 + 3 should be 5"); // expected, actual, message
}
}
Note the imports come from org.junit.jupiter.api — that's the JUnit 5 package, not JUnit 4's org.junit.
Common Mistakes & Pitfalls
- Wrong generation for the intended engine.
org.junit.Testis JUnit 4; it runs on the Platform only when the Vintage engine is present. Jupiter tests importorg.junit.jupiter.api.Test. - Making everything public. Jupiter does not require public test classes or methods, though they must not be private.
- Returning a value. Ordinary Jupiter test methods must return void.
- Assuming every test needs an assertion call. A test may verify through
assertThrows, mocks, or another assertion library, but a method with no observable check usually proves little.
Check your understanding
Answer these without looking back at the article.
- What is the difference between JUnit 4 and JUnit 5?
- How do you run tests with Maven?
- What is the Maven Surefire plugin?
Looking for a structured roadmap?
Every module on this page is also part of the full Java backend interview track.