How can I mock db connection in Spring Boot for testing purpose?

By | December 24, 2017


  1. I am using Spring Cloud with Spring Boot in a microservice, that microservice is loading a DB config information to configure a connection.
  2. I created a test to get the rest interfaces using Swagger for documentation.
  3. I want to disable the loading of DB configuration because is not necessary.

Here is the code:

@ContextConfiguration(classes = {Application.class, Swagger2MarkupTest.class}, loader = SpringApplicationContextLoader.class)

public class Swagger2MarkupTest {

    private WebApplicationContext context;

    private MockMvc mockMvc;

    protected Environment env;

    public void setUp() {
        this.mockMvc = MockMvcBuilders.webAppContextSetup(this.context).build();

    public void convertSwaggerToAsciiDoc() throws Exception {

How can I run the test without loading the database configuration?
Is this possible?


There is an option to fake Spring bean with just plain Spring features. You need to use @Primary, @Profile and @ActiveProfiles annotations for it.

I wrote a blog post on the topic.

You can use in memory DB (e.g. H2) to replace real data source. Something like this:

public class TestingDataSourceConfig {

    public DataSource dataSource() {
        return new EmbeddedDatabaseBuilder()
            .addScripts("user_data.sql", "country_data.sql")

Leave a Reply

Your email address will not be published. Required fields are marked *