CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/maven-junit--junit

JUnit is a unit testing framework for Java, created by Erich Gamma and Kent Beck.

Overview
Eval results
Files

assumptions.mddocs/

Assumptions

The Assume class provides static methods for stating assumptions about the conditions in which a test is meaningful. When an assumption fails, the test is skipped (marked as ignored) rather than failed. This is useful for tests that only make sense in certain environments or configurations.

Note: All methods in this class are static. Do not instantiate this class directly.

Capabilities

Boolean Assumptions

Skip tests when boolean conditions are not met. Most commonly used for environment-specific tests.

/**
 * Skips the test if the condition is false
 * @param condition - Condition that must be true for test to run
 */
public static void assumeTrue(boolean condition);

/**
 * Skips the test if the condition is false
 * @param message - Message explaining the assumption
 * @param condition - Condition that must be true for test to run
 */
public static void assumeTrue(String message, boolean condition);

/**
 * Skips the test if the condition is true
 * @param condition - Condition that must be false for test to run
 */
public static void assumeFalse(boolean condition);

/**
 * Skips the test if the condition is true
 * @param message - Message explaining the assumption
 * @param condition - Condition that must be false for test to run
 */
public static void assumeFalse(String message, boolean condition);

Usage Examples:

import org.junit.Test;
import org.junit.Before;
import static org.junit.Assume.*;
import static org.junit.Assert.*;

public class EnvironmentTest {
    @Test
    public void testOnWindows() {
        assumeTrue(System.getProperty("os.name").contains("Windows"));
        // This test only runs on Windows
        testWindowsSpecificFeature();
    }

    @Test
    public void testOnLinux() {
        assumeTrue("Test requires Linux", isLinux());
        // Skipped on non-Linux systems
        testLinuxFeature();
    }

    @Test
    public void testNotOnMac() {
        assumeFalse(System.getProperty("os.name").contains("Mac"));
        // Skipped on Mac systems
        testNonMacFeature();
    }

    @Before
    public void checkDatabaseAvailable() {
        // Skip all tests in this class if database is not available
        assumeTrue("Database must be available", isDatabaseRunning());
    }
}

Null Assumptions

Skip tests when required objects are null. Useful for optional dependencies or resources.

/**
 * Skips the test if any of the provided objects are null
 * @param objects - Objects that must not be null
 */
public static void assumeNotNull(Object... objects);

Usage Examples:

import org.junit.Test;
import static org.junit.Assume.*;
import static org.junit.Assert.*;

public class DependencyTest {
    @Test
    public void testWithExternalService() {
        ExternalService service = tryConnectToService();
        assumeNotNull(service);
        // Test only runs if connection succeeded
        assertEquals("OK", service.ping());
    }

    @Test
    public void testWithOptionalConfig() {
        Config config = loadOptionalConfig();
        Database db = connectToDatabase();
        assumeNotNull("Need config and database", config, db);
        // Skipped if either is null
        db.configure(config);
    }

    @Test
    public void testWithSystemProperty() {
        String apiKey = System.getProperty("api.key");
        assumeNotNull(apiKey);
        // Only runs if API key is configured
        testApiWithKey(apiKey);
    }
}

Matcher Assumptions

Skip tests based on Hamcrest matcher conditions. Provides expressive, readable assumption logic.

/**
 * Skips the test if the actual value doesn't match the matcher
 * @param actual - Value to check
 * @param matcher - Hamcrest matcher
 */
public static <T> void assumeThat(T actual, Matcher<T> matcher);

/**
 * Skips the test if the actual value doesn't match the matcher
 * @param message - Message explaining the assumption
 * @param actual - Value to check
 * @param matcher - Hamcrest matcher
 */
public static <T> void assumeThat(String message, T actual, Matcher<T> matcher);

Usage Examples:

import org.junit.Test;
import static org.junit.Assume.*;
import static org.junit.Assert.*;
import static org.hamcrest.CoreMatchers.*;

public class MatcherAssumptionTest {
    @Test
    public void testWithMinimumJavaVersion() {
        String version = System.getProperty("java.version");
        assumeThat(version, startsWith("11"));
        // Only runs on Java 11+
        testJava11Feature();
    }

    @Test
    public void testWithSufficientMemory() {
        long freeMemory = Runtime.getRuntime().freeMemory();
        assumeThat("Need at least 100MB free",
                   freeMemory,
                   greaterThan(100_000_000L));
        // Skipped if insufficient memory
        testMemoryIntensiveOperation();
    }

    @Test
    public void testInDevelopmentMode() {
        String environment = getEnvironment();
        assumeThat(environment, either(is("dev")).or(is("test")));
        // Only runs in dev or test environment
        testDevelopmentFeature();
    }

    @Test
    public void testWithFeatureFlag() {
        Set<String> enabledFeatures = getEnabledFeatures();
        assumeThat(enabledFeatures, hasItem("new_feature"));
        // Skipped if feature flag not enabled
        testNewFeature();
    }
}

Exception Assumptions

Skip tests when exceptions occur during assumption checks. Useful for assuming external resources are available.

/**
 * Skips the test if the throwable is not null
 * Used to skip tests when an exception occurred during setup
 * @param t - Throwable to check (null means continue)
 */
public static void assumeNoException(Throwable t);

/**
 * Skips the test if the throwable is not null
 * @param message - Message explaining the assumption
 * @param t - Throwable to check (null means continue)
 */
public static void assumeNoException(String message, Throwable t);

Usage Examples:

import org.junit.Test;
import static org.junit.Assume.*;
import static org.junit.Assert.*;

public class ExceptionAssumptionTest {
    @Test
    public void testDatabaseOperations() {
        Throwable connectionError = null;
        try {
            database.connect();
        } catch (Exception e) {
            connectionError = e;
        }
        assumeNoException("Database must be available", connectionError);
        // Test only runs if connection succeeded
        database.query("SELECT * FROM users");
    }

    @Test
    public void testNetworkResource() {
        Exception networkError = null;
        try {
            pingServer();
        } catch (IOException e) {
            networkError = e;
        }
        assumeNoException(networkError);
        // Skipped if network is unavailable
        testNetworkFeature();
    }

    @Test
    public void testFileAccess() {
        Throwable fileError = tryAccessFile("/data/test.txt");
        assumeNoException("Test file must be accessible", fileError);
        // Skipped if file cannot be accessed
        processTestFile();
    }

    private Throwable tryAccessFile(String path) {
        try {
            new File(path).exists();
            return null;
        } catch (Exception e) {
            return e;
        }
    }
}

Assumption Patterns

Common patterns for using assumptions effectively in test suites.

Usage Examples:

import org.junit.Test;
import org.junit.Before;
import org.junit.BeforeClass;
import static org.junit.Assume.*;

public class AssumptionPatternsTest {
    // Pattern 1: Class-level assumptions
    @BeforeClass
    public static void checkEnvironment() {
        // Skip entire test class if not on CI
        assumeTrue("CI environment required", isCIEnvironment());
    }

    // Pattern 2: Test setup assumptions
    @Before
    public void setupTest() {
        // Skip individual tests if setup fails
        assumeTrue("Database must be running", database.isConnected());
    }

    // Pattern 3: Multiple assumptions combined
    @Test
    public void testComplexScenario() {
        // All assumptions must pass for test to run
        assumeTrue("Must be Linux", isLinux());
        assumeNotNull("Config required", config);
        assumeThat("Java 11+ required", javaVersion(), greaterThanOrEqualTo(11));

        // Test code here
    }

    // Pattern 4: Assumption with fallback
    @Test
    public void testWithFallback() {
        String apiEndpoint = System.getenv("API_ENDPOINT");
        if (apiEndpoint == null) {
            apiEndpoint = "http://localhost:8080";
        }
        assumeNotNull("API must be reachable", pingEndpoint(apiEndpoint));

        testApi(apiEndpoint);
    }

    // Pattern 5: Assumption in parameterized test
    @Test
    public void testBrowserSpecific() {
        String browser = getCurrentBrowser();
        assumeThat(browser, anyOf(is("chrome"), is("firefox")));
        // Test only runs for supported browsers
        testWebFeature();
    }
}

Types

/**
 * Exception thrown when an assumption fails
 * Caught by JUnit to mark test as skipped/ignored
 */
public class AssumptionViolatedException extends RuntimeException {
    public AssumptionViolatedException(String message);
    public AssumptionViolatedException(String message, Throwable cause);
    public AssumptionViolatedException(String assumption, boolean hasValue, Object value);
    public AssumptionViolatedException(String assumption, Object value, Matcher<?> matcher);
}

Differences from Assertions

AspectAssertionsAssumptions
PurposeVerify test expectationsCheck test preconditions
Failure resultTest failsTest skipped/ignored
When to useTesting application behaviorChecking environment/context
Exception thrownAssertionErrorAssumptionViolatedException
Test report statusFailedIgnored/Skipped

When to use Assumptions:

  • Tests that only work in specific environments (OS, Java version, etc.)
  • Tests requiring optional external resources (databases, network services)
  • Tests dependent on feature flags or configuration
  • Tests that need specific hardware or system capabilities
  • Tests that should only run in certain build phases (CI, nightly builds)

When to use Assertions:

  • Verifying the behavior of your code
  • Checking method return values
  • Validating object states
  • Testing business logic
  • All normal test verification

Install with Tessl CLI

npx tessl i tessl/maven-junit--junit

docs

annotations.md

assertions.md

assumptions.md

categories.md

index.md

matchers.md

rules.md

standard-runners.md

test-runners.md

theories.md

tile.json