Created
November 7, 2015 00:37
-
-
Save nsdiv/9effb78e27ff6ca94381 to your computer and use it in GitHub Desktop.
Mock MongoDB when unit testing services with Spring Boot
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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!