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 |
Invest now in Acorns!!! 🚀
Join Acorns and get your $5 bonus!
Acorns is a micro-investing app that automatically invests your "spare change" from daily purchases into diversified, expert-built portfolios of ETFs. It is designed for beginners, allowing you to start investing with as little as $5. The service automates saving and investing. Disclosure: I may receive a referral bonus.
Invest now!!! Get Free equity stock (US, UK only)!
Use Robinhood app to invest in stocks. It is safe and secure. Use the Referral link to claim your free stock when you sign up!.
The Robinhood app makes it easy to trade stocks, crypto and more.
Webull! Receive free stock by signing up using the link: Webull signup.
More Related questions...
