0
# Assumptions
1
2
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.
3
4
**Note:** All methods in this class are static. Do not instantiate this class directly.
5
6
## Capabilities
7
8
### Boolean Assumptions
9
10
Skip tests when boolean conditions are not met. Most commonly used for environment-specific tests.
11
12
```java { .api }
13
/**
14
* Skips the test if the condition is false
15
* @param condition - Condition that must be true for test to run
16
*/
17
public static void assumeTrue(boolean condition);
18
19
/**
20
* Skips the test if the condition is false
21
* @param message - Message explaining the assumption
22
* @param condition - Condition that must be true for test to run
23
*/
24
public static void assumeTrue(String message, boolean condition);
25
26
/**
27
* Skips the test if the condition is true
28
* @param condition - Condition that must be false for test to run
29
*/
30
public static void assumeFalse(boolean condition);
31
32
/**
33
* Skips the test if the condition is true
34
* @param message - Message explaining the assumption
35
* @param condition - Condition that must be false for test to run
36
*/
37
public static void assumeFalse(String message, boolean condition);
38
```
39
40
**Usage Examples:**
41
42
```java
43
import org.junit.Test;
44
import org.junit.Before;
45
import static org.junit.Assume.*;
46
import static org.junit.Assert.*;
47
48
public class EnvironmentTest {
49
@Test
50
public void testOnWindows() {
51
assumeTrue(System.getProperty("os.name").contains("Windows"));
52
// This test only runs on Windows
53
testWindowsSpecificFeature();
54
}
55
56
@Test
57
public void testOnLinux() {
58
assumeTrue("Test requires Linux", isLinux());
59
// Skipped on non-Linux systems
60
testLinuxFeature();
61
}
62
63
@Test
64
public void testNotOnMac() {
65
assumeFalse(System.getProperty("os.name").contains("Mac"));
66
// Skipped on Mac systems
67
testNonMacFeature();
68
}
69
70
@Before
71
public void checkDatabaseAvailable() {
72
// Skip all tests in this class if database is not available
73
assumeTrue("Database must be available", isDatabaseRunning());
74
}
75
}
76
```
77
78
### Null Assumptions
79
80
Skip tests when required objects are null. Useful for optional dependencies or resources.
81
82
```java { .api }
83
/**
84
* Skips the test if any of the provided objects are null
85
* @param objects - Objects that must not be null
86
*/
87
public static void assumeNotNull(Object... objects);
88
```
89
90
**Usage Examples:**
91
92
```java
93
import org.junit.Test;
94
import static org.junit.Assume.*;
95
import static org.junit.Assert.*;
96
97
public class DependencyTest {
98
@Test
99
public void testWithExternalService() {
100
ExternalService service = tryConnectToService();
101
assumeNotNull(service);
102
// Test only runs if connection succeeded
103
assertEquals("OK", service.ping());
104
}
105
106
@Test
107
public void testWithOptionalConfig() {
108
Config config = loadOptionalConfig();
109
Database db = connectToDatabase();
110
assumeNotNull("Need config and database", config, db);
111
// Skipped if either is null
112
db.configure(config);
113
}
114
115
@Test
116
public void testWithSystemProperty() {
117
String apiKey = System.getProperty("api.key");
118
assumeNotNull(apiKey);
119
// Only runs if API key is configured
120
testApiWithKey(apiKey);
121
}
122
}
123
```
124
125
### Matcher Assumptions
126
127
Skip tests based on Hamcrest matcher conditions. Provides expressive, readable assumption logic.
128
129
```java { .api }
130
/**
131
* Skips the test if the actual value doesn't match the matcher
132
* @param actual - Value to check
133
* @param matcher - Hamcrest matcher
134
*/
135
public static <T> void assumeThat(T actual, Matcher<T> matcher);
136
137
/**
138
* Skips the test if the actual value doesn't match the matcher
139
* @param message - Message explaining the assumption
140
* @param actual - Value to check
141
* @param matcher - Hamcrest matcher
142
*/
143
public static <T> void assumeThat(String message, T actual, Matcher<T> matcher);
144
```
145
146
**Usage Examples:**
147
148
```java
149
import org.junit.Test;
150
import static org.junit.Assume.*;
151
import static org.junit.Assert.*;
152
import static org.hamcrest.CoreMatchers.*;
153
154
public class MatcherAssumptionTest {
155
@Test
156
public void testWithMinimumJavaVersion() {
157
String version = System.getProperty("java.version");
158
assumeThat(version, startsWith("11"));
159
// Only runs on Java 11+
160
testJava11Feature();
161
}
162
163
@Test
164
public void testWithSufficientMemory() {
165
long freeMemory = Runtime.getRuntime().freeMemory();
166
assumeThat("Need at least 100MB free",
167
freeMemory,
168
greaterThan(100_000_000L));
169
// Skipped if insufficient memory
170
testMemoryIntensiveOperation();
171
}
172
173
@Test
174
public void testInDevelopmentMode() {
175
String environment = getEnvironment();
176
assumeThat(environment, either(is("dev")).or(is("test")));
177
// Only runs in dev or test environment
178
testDevelopmentFeature();
179
}
180
181
@Test
182
public void testWithFeatureFlag() {
183
Set<String> enabledFeatures = getEnabledFeatures();
184
assumeThat(enabledFeatures, hasItem("new_feature"));
185
// Skipped if feature flag not enabled
186
testNewFeature();
187
}
188
}
189
```
190
191
### Exception Assumptions
192
193
Skip tests when exceptions occur during assumption checks. Useful for assuming external resources are available.
194
195
```java { .api }
196
/**
197
* Skips the test if the throwable is not null
198
* Used to skip tests when an exception occurred during setup
199
* @param t - Throwable to check (null means continue)
200
*/
201
public static void assumeNoException(Throwable t);
202
203
/**
204
* Skips the test if the throwable is not null
205
* @param message - Message explaining the assumption
206
* @param t - Throwable to check (null means continue)
207
*/
208
public static void assumeNoException(String message, Throwable t);
209
```
210
211
**Usage Examples:**
212
213
```java
214
import org.junit.Test;
215
import static org.junit.Assume.*;
216
import static org.junit.Assert.*;
217
218
public class ExceptionAssumptionTest {
219
@Test
220
public void testDatabaseOperations() {
221
Throwable connectionError = null;
222
try {
223
database.connect();
224
} catch (Exception e) {
225
connectionError = e;
226
}
227
assumeNoException("Database must be available", connectionError);
228
// Test only runs if connection succeeded
229
database.query("SELECT * FROM users");
230
}
231
232
@Test
233
public void testNetworkResource() {
234
Exception networkError = null;
235
try {
236
pingServer();
237
} catch (IOException e) {
238
networkError = e;
239
}
240
assumeNoException(networkError);
241
// Skipped if network is unavailable
242
testNetworkFeature();
243
}
244
245
@Test
246
public void testFileAccess() {
247
Throwable fileError = tryAccessFile("/data/test.txt");
248
assumeNoException("Test file must be accessible", fileError);
249
// Skipped if file cannot be accessed
250
processTestFile();
251
}
252
253
private Throwable tryAccessFile(String path) {
254
try {
255
new File(path).exists();
256
return null;
257
} catch (Exception e) {
258
return e;
259
}
260
}
261
}
262
```
263
264
### Assumption Patterns
265
266
Common patterns for using assumptions effectively in test suites.
267
268
**Usage Examples:**
269
270
```java
271
import org.junit.Test;
272
import org.junit.Before;
273
import org.junit.BeforeClass;
274
import static org.junit.Assume.*;
275
276
public class AssumptionPatternsTest {
277
// Pattern 1: Class-level assumptions
278
@BeforeClass
279
public static void checkEnvironment() {
280
// Skip entire test class if not on CI
281
assumeTrue("CI environment required", isCIEnvironment());
282
}
283
284
// Pattern 2: Test setup assumptions
285
@Before
286
public void setupTest() {
287
// Skip individual tests if setup fails
288
assumeTrue("Database must be running", database.isConnected());
289
}
290
291
// Pattern 3: Multiple assumptions combined
292
@Test
293
public void testComplexScenario() {
294
// All assumptions must pass for test to run
295
assumeTrue("Must be Linux", isLinux());
296
assumeNotNull("Config required", config);
297
assumeThat("Java 11+ required", javaVersion(), greaterThanOrEqualTo(11));
298
299
// Test code here
300
}
301
302
// Pattern 4: Assumption with fallback
303
@Test
304
public void testWithFallback() {
305
String apiEndpoint = System.getenv("API_ENDPOINT");
306
if (apiEndpoint == null) {
307
apiEndpoint = "http://localhost:8080";
308
}
309
assumeNotNull("API must be reachable", pingEndpoint(apiEndpoint));
310
311
testApi(apiEndpoint);
312
}
313
314
// Pattern 5: Assumption in parameterized test
315
@Test
316
public void testBrowserSpecific() {
317
String browser = getCurrentBrowser();
318
assumeThat(browser, anyOf(is("chrome"), is("firefox")));
319
// Test only runs for supported browsers
320
testWebFeature();
321
}
322
}
323
```
324
325
## Types
326
327
```java { .api }
328
/**
329
* Exception thrown when an assumption fails
330
* Caught by JUnit to mark test as skipped/ignored
331
*/
332
public class AssumptionViolatedException extends RuntimeException {
333
public AssumptionViolatedException(String message);
334
public AssumptionViolatedException(String message, Throwable cause);
335
public AssumptionViolatedException(String assumption, boolean hasValue, Object value);
336
public AssumptionViolatedException(String assumption, Object value, Matcher<?> matcher);
337
}
338
```
339
340
## Differences from Assertions
341
342
| Aspect | Assertions | Assumptions |
343
|--------|-----------|-------------|
344
| Purpose | Verify test expectations | Check test preconditions |
345
| Failure result | Test fails | Test skipped/ignored |
346
| When to use | Testing application behavior | Checking environment/context |
347
| Exception thrown | `AssertionError` | `AssumptionViolatedException` |
348
| Test report status | Failed | Ignored/Skipped |
349
350
**When to use Assumptions:**
351
352
- Tests that only work in specific environments (OS, Java version, etc.)
353
- Tests requiring optional external resources (databases, network services)
354
- Tests dependent on feature flags or configuration
355
- Tests that need specific hardware or system capabilities
356
- Tests that should only run in certain build phases (CI, nightly builds)
357
358
**When to use Assertions:**
359
360
- Verifying the behavior of your code
361
- Checking method return values
362
- Validating object states
363
- Testing business logic
364
- All normal test verification
365