Skip to content

Commit f2d9987

Browse files
committed
Add TemporaryNetwork Rule
1 parent 3fb74aa commit f2d9987

File tree

2 files changed

+63
-1
lines changed

2 files changed

+63
-1
lines changed

core/src/test/java/org/testcontainers/containers/NetworkTest.java

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77
import org.testcontainers.DockerClientFactory;
88
import org.testcontainers.TestImages;
99
import org.testcontainers.junit.vintage.Container;
10+
import org.testcontainers.junit.vintage.TemporaryNetwork;
1011
import org.testcontainers.junit.vintage.Testcontainers;
1112

1213
import static org.assertj.core.api.Assertions.assertThat;
@@ -17,7 +18,7 @@ public class NetworkTest {
1718
public static class WithRules {
1819

1920
@Rule
20-
public Network network = Network.newNetwork();
21+
public TemporaryNetwork network = new TemporaryNetwork(Network.newNetwork());
2122

2223
@Rule
2324
public Testcontainers containers = new Testcontainers(this);
Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
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+
}

0 commit comments

Comments
 (0)