# Assumptions and Conditional Execution — JUnit 5 & Mockito

Source: https://www.skillbyai.com/en/java-testing/a-conditions

> Skip tests conditionally with assumptions and enable/disable annotations.

## Running tests only where they make sense

Some tests should run only in certain environments: on Linux, with a specific Java version, when an environment variable or system property is set, or only on CI. **Conditional annotations** decide before a test runs: `@EnabledOnOs(OS.LINUX)`, `@DisabledOnOs(OS.WINDOWS)`, `@EnabledOnJre(JRE.JAVA_21)`, `@EnabledForJreRange`, `@EnabledIfEnvironmentVariable(named = "CI", matches = "true")`, `@EnabledIfSystemProperty`, and `@EnabledIf("methodName")` for custom logic. **Assumptions** decide **inside** a test: `assumeTrue(condition)` aborts the test (reported as **skipped**, not failed) when the condition is false, and `assumingThat(condition, executable)` runs part of a test only if the condition holds. Use these for genuine environment differences, such as tests that need Docker or a GPU. Do not use them to hide failing tests: a skipped test gives no protection, and a suite full of skipped tests gives false confidence. Report skipped counts in CI so they stay visible.

## Environment-dependent tests

Skipped tests are reported separately from passed and failed ones.

```java
class FileSystemTest {

    @Test
    @EnabledOnOs({OS.LINUX, OS.MAC})
    void handlesPosixPermissions(@TempDir Path dir) throws IOException {
        Path f = Files.createFile(dir.resolve("secret.txt"));
        Files.setPosixFilePermissions(f, PosixFilePermissions.fromString("rw-------"));
        assertThat(Files.getPosixFilePermissions(f)).hasSize(2);
    }

    @Test
    @EnabledIfEnvironmentVariable(named = "CI", matches = "true")
    void runsOnlyInCi() { /* expensive check */ }

    @Test
    void usesDockerWhenAvailable() {
        assumeTrue(DockerProbe.isAvailable(), "Docker not available");   // skipped, not failed
        // integration assertions ...
    }
}
```

## An outdoor match and the weather

An assumption is like a cricket match called off for rain: it is not a loss for either team, just not played. But a season where every match is rained off tells you nothing about who is better.

**Quiz:** What happens when assumeTrue(false) is called inside a test?

- [ ] The test fails
- [ ] The JVM exits
- [ ] The assertion is ignored and the test passes
- [x] The test is aborted and reported as skipped

*Answer:* The test is aborted and reported as skipped. Failed assumptions abort the test as skipped rather than failed.
