mongo-java-server icon indicating copy to clipboard operation
mongo-java-server copied to clipboard

junit5 extensions

Open nhomble opened this issue 4 years ago • 2 comments

I love this library and I use it all the time. I find my test code has the same boiler plate (mostly taken from the README) in every test. Are there any concerns with adding another module that would house the test harnesses?

A junit extension could handle the lifecycle of the mongo server and allow test methods to inject the client as a parameter as needed.

nhomble avatar Apr 05 '20 23:04 nhomble

A JUnit extension would definitely be nice.

In the meantime you can also outsource the "boiler plate code" used for the mongo-java-server configuration to a separate class ...

public class MongoTestServerConfiguration {
	@Bean
	public MongoTemplate mongoTemplate(MongoClient mongoClient) {
		return new MongoTemplate(mongoDbFactory(mongoClient));
	}

	@Bean
	public MongoDbFactory mongoDbFactory(MongoClient mongoClient) {
		return new SimpleMongoClientDbFactory(mongoClient, "test");
	}

	@Bean(destroyMethod="shutdown")
	public MongoServer mongoServer() {
		MongoServer mongoServer = new MongoServer(new MemoryBackend());
		mongoServer.bind();
		return mongoServer;
	}

	@Bean(destroyMethod="close")
	public MongoClient mongoClient(MongoServer mongoServer) {
		return MongoClients.create("mongodb://" + mongoServer.getLocalAddress().getHostName() + ":" + mongoServer.getLocalAddress().getPort());
	}
}

... and import it in all your tests:

@RunWith(SpringRunner.class)
@SpringBootTest(classes={MyTest.TestConfiguration.class})
public class MyTest {

	// @Test ...

	@Configuration
	@Import({MongoTestServerConfiguration.class})
	@EnableMongoRepositories(basePackageClasses={MyRepository.class})
	protected static class TestConfiguration {
		// ...
	}
}

Or you can create an annotation like this ...

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Import(MongoTestServerConfiguration.class)
public @interface EnableMongoTestServer {
}

... and use it in your test:

@RunWith(SpringRunner.class)
@SpringBootTest(classes={MyTest.TestConfiguration.class})
public class MyTest {

	// @Test ...

	@Configuration
	@EnableMongoRepositories(basePackageClasses={MyRepository.class})
	@EnableMongoTestServer
	protected static class TestConfiguration {
		// ...
	}
}

markbigler avatar Apr 06 '20 09:04 markbigler

Yes, such an extension would make sense. I would be happy to review/merge a pull request.

bwaldvogel avatar Apr 06 '20 09:04 bwaldvogel