これまでのところ、 fakemongoの使用を勧められた人が誰もいなかったことに驚いています。これは mongo クライアントをかなりうまくエミュレートし、すべて同じ JVM でテストを実行します。そのため、外部システムとの相互作用が発生しないため、統合テストが堅牢になり、技術的に真の「単体テスト」にはるかに近くなります。これは、埋め込まれた H2 を使用して SQL コードの単体テストを行うようなものです。データベース統合コードをエンドツーエンドでテストする単体テストで、fakemongo を使用できてとても満足しています。テストスプリングのコンテキストでこの構成を検討してください。
@Configuration
@Slf4j
public class FongoConfig extends AbstractMongoConfiguration {
@Override
public String getDatabaseName() {
return "mongo-test";
}
@Override
@Bean
public Mongo mongo() throws Exception {
log.info("Creating Fake Mongo instance");
return new Fongo("mongo-test").getMongo();
}
@Bean
@Override
public MongoTemplate mongoTemplate() throws Exception {
return new MongoTemplate(mongo(), getDatabaseName());
}
}
これにより、Spring コンテキストから MongoTemplate を使用するコードをテストでき、nosql-unit、jsonunitなどと組み合わせて、mongo クエリ コードをカバーする堅牢な単体テストを取得できます。
@Test
@UsingDataSet(locations = {"/TSDR1326-data/TSDR1326-subject.json"}, loadStrategy = LoadStrategyEnum.CLEAN_INSERT)
@DatabaseSetup({"/TSDR1326-data/dbunit-TSDR1326.xml"})
public void shouldCleanUploadSubjectCollection() throws Exception {
//given
JobParameters jobParameters = new JobParametersBuilder()
.addString("studyId", "TSDR1326")
.addString("execId", UUID.randomUUID().toString())
.toJobParameters();
//when
//next line runs a Spring Batch ETL process loading data from SQL DB(H2) into Mongo
final JobExecution res = jobLauncherTestUtils.launchJob(jobParameters);
//then
assertThat(res.getExitStatus()).isEqualTo(ExitStatus.COMPLETED);
final String resultJson = mongoTemplate.find(new Query().with(new Sort(Sort.Direction.ASC, "topLevel.subjectId.value")),
DBObject.class, "subject").toString();
assertThatJson(resultJson).isArray().ofLength(3);
assertThatDateNode(resultJson, "[0].topLevel.timestamp.value").isEqualTo(res.getStartTime());
assertThatNode(resultJson, "[0].topLevel.subjectECode.value").isStringEqualTo("E01");
assertThatDateNode(resultJson, "[0].topLevel.subjectECode.timestamp").isEqualTo(res.getStartTime());
... etc
}
私は mongo 3.4 ドライバーで問題なく fakemongo を使用しており、コミュニティは 3.6 ドライバーをサポートするバージョンをリリースするのに非常に近いです ( https://github.com/fakemongo/fongo/issues/316 )。