简体   繁体   中英

Spring Boot Exclude DataSource Configuration

I have a small application that when live, makes a database connection, and stores and persists some data.

I'm currently in the midsts of trying to write some tests, and I'm wanting to completely cut off the database part of the application, and just mock it in the tests.

The Datasource is setup with a configuration class.

@Component
@Configuration
public class DataSourceConfiguration {
    @Bean
    public DataSource myDataSource() { ... }
}

and a test boostrap that currently looks similar to

@RunWith(SpringRunner.class)
@EnableAutoConfiguration(exclude = {
    DataSourceAutoConfiguration.class,
    DataSourceTransactionManagerAutoConfiguration.class,
    HibernateJpaAutoConfiguration.class
})
public class MyTest {
}

When running the test, I can see that Spring is trying to instantiate Hibernate, and a connection to the db, I assume because of my config class. How can I stop Spring from doing this?

No Need to use : @EnableAutoConfiguration

We can narrow down the tests to just the web layer by using @WebMvcTest as below,

@RunWith(SpringRunner.class)
@WebMvcTest
public class WebLayerTest {

    @Autowired
    private MockMvc mockMvc;

    @Test
    public void shouldReturnDefaultMessage() throws Exception {
    this.mockMvc.perform(get("/")).andDo(print()).andExpect(status().isOk())
            .andExpect(content().string(containsString("Hello World")));
    }
}

Refer how to test spring application with only web or using complete application context loading : https://spring.io/guides/gs/testing-web/

refer mocking example : http://www.lucassaldanha.com/unit-and-integration-tests-in-spring-boot/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM