Testing / JUnit6 Interview Questions
What are assumptions in JUnit 6 and how do they differ from assertions?
Assumptions abort a test silently (marking it as aborted) when a condition is not met. Assertions fail the test with a failure when a condition is not met. Use assumptions to skip tests that are irrelevant in the current environment rather than to verify business logic.
import static org.junit.jupiter.api.Assumptions.*; class AssumptionsDemo { @Test void runOnlyOnLinux() { assumeTrue(System.getProperty("os.name").toLowerCase().contains("linux"), "Skipped: not running on Linux"); // Test body: only executes on Linux // On Windows/macOS: test is ABORTED (not failed) } @Test void runOnlyInCiEnvironment() { // assumingThat: execute body only if condition true; continue otherwise assumingThat( "CI".equals(System.getenv("ENV")), () -> { // This block runs only in CI verifyDeploymentHealth(); } ); // This line always runs regardless of the assumption assertEquals(1, 1); } @Test void skipOnNullDatabase() { assumeFalse(System.getenv("DB_URL") == null, "Skipped: DB_URL not configured"); // Integration test body } }
| Aspect | Assumptions | Assertions |
|---|---|---|
| Failure mode | Test aborted (grey in reports) | Test failed (red in reports) |
| Use case | Skip irrelevant test in current environment | Verify correctness of production logic |
| Methods | assumeTrue, assumeFalse, assumingThat | assertEquals, assertTrue, assertThrows etc. |
| Effect on suite | Skipped: does not count as pass or fail | Failure: counts against the build |
More Related questions...