|
33 | 33 |
|
34 | 34 | /**
|
35 | 35 | * A {@link ContextStorage} which keeps track of opened and closed {@link Scope}s, reporting caller
|
36 |
| - * information if a {@link Scope} is closed incorrectly or not at all. This is useful in |
37 |
| - * instrumentation tests to check whether any scopes leaked. |
| 36 | + * information if a {@link Scope} is closed incorrectly or not at all. |
38 | 37 | *
|
39 |
| - * <pre>{@code |
40 |
| - * > class MyInstrumentationTest { |
41 |
| - * > private static ContextStorage previousStorage; |
42 |
| - * > private static StrictContextStorage strictStorage; |
43 |
| - * > |
44 |
| - * > @BeforeAll |
45 |
| - * > static void setUp() { |
46 |
| - * > previousStorage = ContextStorage.get() |
47 |
| - * > strictStorage = StrictContextStorage.create(previousStorage); |
48 |
| - * > ContextStorage.set(strictStorage); |
49 |
| - * > } |
50 |
| - * > |
51 |
| - * > @AfterEach |
52 |
| - * > void checkScopes() { |
53 |
| - * > strictStorage.ensureAllClosed(); |
54 |
| - * > } |
55 |
| - * > |
56 |
| - * > @AfterAll |
57 |
| - * > static void tearDown() { |
58 |
| - * > ContextStorage.set(previousStorage); |
59 |
| - * > } |
60 |
| - * > |
61 |
| - * > @Test |
62 |
| - * > void badTest() { |
63 |
| - * > Context.root().makeCurrent(); |
64 |
| - * > } |
65 |
| - * > } |
66 |
| - * }</pre> |
| 38 | + * <p>Calling {@link StrictContextStorage#close()} will check at the moment it's called whether |
| 39 | + * there are any scopes that have been opened but not closed yet. This could be called at the end of |
| 40 | + * a unit test to ensure the tested code cleaned up scopes correctly. |
67 | 41 | */
|
68 |
| -final class StrictContextStorage implements ContextStorage { |
| 42 | +final class StrictContextStorage implements ContextStorage, AutoCloseable { |
69 | 43 |
|
70 | 44 | /**
|
71 | 45 | * Returns a new {@link StrictContextStorage} which delegates to the provided {@link
|
@@ -153,8 +127,8 @@ public Context current() {
|
153 | 127 | * @throws AssertionError if any scopes were left unclosed.
|
154 | 128 | */
|
155 | 129 | // AssertionError to ensure test runners render the stack trace
|
156 |
| - // Visible for testing |
157 |
| - void ensureAllClosed() { |
| 130 | + @Override |
| 131 | + public void close() { |
158 | 132 | pendingScopes.expungeStaleEntries();
|
159 | 133 | List<CallerStackTrace> leaked = pendingScopes.drainPendingCallers();
|
160 | 134 | if (!leaked.isEmpty()) {
|
|
0 commit comments