File tree Expand file tree Collapse file tree 2 files changed +63
-1
lines changed
core/src/test/java/org/testcontainers/containers
modules/junit-vintage/src/main/java/org/testcontainers/junit/vintage Expand file tree Collapse file tree 2 files changed +63
-1
lines changed Original file line number Diff line number Diff line change 7
7
import org .testcontainers .DockerClientFactory ;
8
8
import org .testcontainers .TestImages ;
9
9
import org .testcontainers .junit .vintage .Container ;
10
+ import org .testcontainers .junit .vintage .TemporaryNetwork ;
10
11
import org .testcontainers .junit .vintage .Testcontainers ;
11
12
12
13
import static org .assertj .core .api .Assertions .assertThat ;
@@ -17,7 +18,7 @@ public class NetworkTest {
17
18
public static class WithRules {
18
19
19
20
@ Rule
20
- public Network network = Network .newNetwork ();
21
+ public TemporaryNetwork network = new TemporaryNetwork ( Network .newNetwork () );
21
22
22
23
@ Rule
23
24
public Testcontainers containers = new Testcontainers (this );
Original file line number Diff line number Diff line change
1
+ package org .testcontainers .junit .vintage ;
2
+
3
+ import org .junit .rules .ExternalResource ;
4
+ import org .testcontainers .containers .Network ;
5
+
6
+ /**
7
+ * Integrates {@link Network} with the JUnit4 lifecycle.
8
+ */
9
+ public final class TemporaryNetwork extends ExternalResource implements Network {
10
+
11
+ private final Network network ;
12
+
13
+ private volatile State state = State .BEFORE_RULE ;
14
+
15
+ /**
16
+ * Creates an instance.
17
+ *
18
+ * <p>The passed-in network will be closed when the current test completes.
19
+ *
20
+ * @param network Network that the rule will delegate to.
21
+ */
22
+ public TemporaryNetwork (Network network ) {
23
+ this .network = network ;
24
+ }
25
+
26
+ @ Override
27
+ public String getId () {
28
+ if (state == State .AFTER_RULE ) {
29
+ throw new IllegalStateException ("Cannot get the network ID after the test completes" );
30
+ }
31
+ return network .getId ();
32
+ }
33
+
34
+ @ Override
35
+ public void close () {
36
+ if (state != State .INSIDE_RULE ) {
37
+ throw new IllegalStateException ("Cannot close the network outside of the context of the rule" );
38
+ }
39
+ network .close ();
40
+ }
41
+
42
+ @ Override
43
+ protected void before () throws Throwable {
44
+ state = State .AFTER_RULE ; // Just in case an exception is thrown below.
45
+ network .getId (); // This has the side-effect of creating the network.
46
+
47
+ state = State .INSIDE_RULE ;
48
+ }
49
+
50
+ @ Override
51
+ protected void after () {
52
+ state = State .AFTER_RULE ;
53
+ network .close ();
54
+ }
55
+
56
+ private enum State {
57
+ BEFORE_RULE ,
58
+ INSIDE_RULE ,
59
+ AFTER_RULE ,
60
+ }
61
+ }
You can’t perform that action at this time.
0 commit comments