Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
JUnit Suite Class example working with Spring and embedded instance of MongoDB to create Integration Tests
import java.io.IOException;
import java.net.UnknownHostException;
import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import org.junit.After;
import org.junit.BeforeClass;
import org.junit.runner.RunWith;
import org.junit.runners.Suite;
import org.junit.runners.Suite.SuiteClasses;
import org.springframework.stereotype.Component;
import de.flapdoodle.embed.mongo.MongodExecutable;
import de.flapdoodle.embed.mongo.MongodProcess;
import de.flapdoodle.embed.mongo.MongodStarter;
import de.flapdoodle.embed.mongo.config.IMongodConfig;
import de.flapdoodle.embed.mongo.config.MongodConfigBuilder;
import de.flapdoodle.embed.mongo.config.Net;
import de.flapdoodle.embed.mongo.distribution.Version;
/**
This is a Spring with Junit SuiteClasses example that execute a SomeService resource with Embedded Mongo.
See https://github.com/flapdoodle-oss/de.flapdoodle.embed.mongo.
*/
@RunWith(Suite.class)
@SuiteClasses({ Class1IntegrationTests.class, Class2IntegrationTests.class }) // classes to test
@Component // To start Spring Resources
public class AllIntegrationTests {
static MongodStarter starter = MongodStarter.getDefaultInstance();
static MongodExecutable mongodExecutable;
@Resource
SomeService someService;
@PostConstruct
public void construct(){
someService.doSomething();
someService.saveSomeDataInMongo();
}
@BeforeClass
public static void init() throws UnknownHostException, IOException {
// Using a MongoDBConstants with url and db port. To run a Embedded Mongo I used the url localhost and port 12345
IMongodConfig mongodConfig = new MongodConfigBuilder().version(Version.Main.PRODUCTION).net(new Net(MongoDBConstants.MONGO_DB_URL, MongoDBConstants.MONGO_DB_PORT, true)).build();
mongodExecutable = starter.prepare(mongodConfig);
MongodProcess mongod = mongodExecutable.start();
}
@After
public static void shutDown() {
if (mongodExecutable != null){
mongodExecutable.stop();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment