Skip to content

Instantly share code, notes, and snippets.

@nsdiv
Created November 7, 2015 00:37
Show Gist options
  • Save nsdiv/9effb78e27ff6ca94381 to your computer and use it in GitHub Desktop.
Save nsdiv/9effb78e27ff6ca94381 to your computer and use it in GitHub Desktop.
Mock MongoDB when unit testing services with Spring Boot
If you are using Spring Boot with MongoDB, then a MongoDB connection is required even if you are unit testing a function.
Spring creates a connection to mongoDB during start up, because of Autowired beans in your code. This slows down your unit tests, and
also means your unit tests require access to the MongoDB server.
Here is what you need to do:
1. Mock the beans created by org.springframework.boot.autoconfigure.data.mongo.MongoDataAutoConfiguration:
@Bean
public MongoDbFactory mongoDbFactory(){
return null;
}
@Bean
public MongoTemplate mongoTemplate(){
return null;
}
@Bean
public MappingMongoConverter mappingMongoConverter(){
return null;
}
@Bean
public MongoMappingContext mongoMappingContext(){
return null;
}
@Bean
public GridFsTemplate gridFsTemplate(){
return null;
}
2. If you have the MongoHealthCheckIndicator running (you probably have that), then you need to disable it for the test profile:
management.health.mongo.enabled: false
@raulgd
Copy link

raulgd commented Jun 26, 2016

can you share the full autoconfiguration mock class you created? or a more functional example? this seems great but I haven't been able to get it to work.

Thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment