Testing / JUnit6 Interview Questions
What are assumptions in JUnit 6 and how do they differ from assertions?
Assumptions are conditions checked at the start of a test. If an assumption fails, the test is aborted (skipped) rather than failed. Assumptions are used to skip tests that are not meaningful in a particular environment (e.g. running only on Linux, only with network access, only when a feature flag is enabled).
import static org.junit.jupiter.api.Assumptions.*; class AssumptionsDemo { @Test void runOnlyOnCi() { // Abort (skip) the test if CI environment variable is not set assumeTrue("true".equals(System.getenv("CI")), "Skipping: not running in CI environment"); // Test only executes here if the assumption held performSlowIntegrationTest(); } @Test void runOnlyOnLinux() { assumeTrue(System.getProperty("os.name").startsWith("Linux")); // OS-specific test code } @Test void assumptionWithSupplierMessage() { // Lazy message evaluation String env = System.getenv("APP_ENV"); assumeFalse("production".equals(env), () -> "Skipping destructive test in env: " + env); cleanDatabase(); } @Test void runSubsetOnlyWhenDatabaseAvailable() { // assumingThat: run a block only if condition holds // but do NOT abort the whole test boolean dbAvailable = isDatabaseAvailable(); assumingThat(dbAvailable, () -> { // Only this block is skipped if db is unavailable assertDbRecordExists("user-1"); }); // This assertion always runs: assertFalse(dbAvailable && isReadOnly()); } }
| Aspect | Assertion (assertXxx) | Assumption (assumeXxx) |
|---|---|---|
| Failure effect | Test FAILS (red) | Test ABORTED/skipped (grey) |
| Purpose | Verify correctness | Guard against meaningless environments |
| Report visibility | Always shown as failure | Shown as skipped/aborted |
More Related questions...