]> git.somenet.org - pub/jan/dst18.git/blob - ass1-doc/src/test/java/dst/ass1/doc/EmbeddedMongo.java
Add template for assignment 1
[pub/jan/dst18.git] / ass1-doc / src / test / java / dst / ass1 / doc / EmbeddedMongo.java
1 package dst.ass1.doc;
2
3 import java.io.IOException;
4 import java.net.BindException;
5 import java.net.ServerSocket;
6
7 import org.junit.rules.ExternalResource;
8
9 import de.flapdoodle.embed.mongo.config.IMongodConfig;
10 import de.flapdoodle.embed.mongo.config.MongodConfigBuilder;
11 import de.flapdoodle.embed.mongo.config.Net;
12 import de.flapdoodle.embed.mongo.distribution.IFeatureAwareVersion;
13 import de.flapdoodle.embed.mongo.distribution.Version;
14 import de.flapdoodle.embed.mongo.tests.MongodForTestsFactory;
15
16 /**
17  * JUnit rule that creates an in-memory instance of MongoDB using the flapdoodle Embedded MongoDB.
18  */
19 public class EmbeddedMongo extends ExternalResource {
20
21     private MongodForTestsFactory mongod;
22
23     @Override
24     protected void before() throws Throwable {
25         requirePort();
26         mongod = new MongodFactory(); // starts process in constructor
27     }
28
29     @Override
30     protected void after() {
31         if (mongod != null) {
32             mongod.shutdown();
33         }
34     }
35
36     private void requirePort() throws IOException, IllegalStateException {
37         try (ServerSocket ignore = new ServerSocket(27017)) {
38             // ignore
39         } catch (BindException e) {
40             throw new IllegalStateException("Could not bind port 27017 which is necessary to run the MongoDB tests", e);
41         }
42     }
43
44     public static class MongodFactory extends MongodForTestsFactory {
45
46         public MongodFactory() throws IOException {
47             super(Version.Main.V3_5);
48         }
49
50         @Override
51         protected IMongodConfig newMongodConfig(IFeatureAwareVersion version) throws IOException {
52             return new MongodConfigBuilder()
53                     .net(new Net(27017, false))
54                     .version(version)
55                     .build();
56         }
57     }
58 }