Java 如何在 Spring Boot 中模拟数据库连接以进行测试?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/35707469/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 17:02:00  来源:igfitidea点击:

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

javaspringjunitspring-bootspring-test

提问by Rys

Situation:

情况:

  1. I am using Spring Cloudwith Spring Bootin 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 Swaggerfor documentation.
  3. I want to disable the loading of DB configuration because is not necessary.
  1. 我在微服务中使用Spring Cloudwith Spring Boot,该微服务正在加载数据库配置信息以配置连接。
  2. 我创建了一个测试来获取Swagger用于文档的其余接口。
  3. 我想禁用数据库配置的加载,因为没有必要。

Here is the code:

这是代码:

@WebAppConfiguration
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {Application.class, Swagger2MarkupTest.class}, loader = SpringApplicationContextLoader.class)
@ActiveProfiles("test")

public class Swagger2MarkupTest {

    @Autowired
    private WebApplicationContext context;

    private MockMvc mockMvc;

    @Autowired
    protected Environment env;

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

    @Test
    public void convertSwaggerToAsciiDoc() throws Exception {
        this.mockMvc.perform(get("/v2/api-docs").accept(MediaType.APPLICATION_JSON))
                .andDo(Swagger2MarkupResultHandler.outputDirectory("target/docs/asciidoc/generated")
                        .withExamples("target/docs/asciidoc/generated/exampless").build())
                .andExpect(status().isOk());
    }
}

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

如何在不加载数据库配置的情况下运行测试?这可能吗?

采纳答案by luboskrnac

There is an option to fake Spring bean with just plain Spring features. You need to use @Primary, @Profileand @ActiveProfilesannotations for it.

有一个选项可以使用普通的 Spring 功能来伪造 Spring bean。您需要使用@Primary,@Profile@ActiveProfiles注释。

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:

您可以在内存中使用 DB(例如 H2)来替换真实数据源。像这样的东西:

@Configuration
public class TestingDataSourceConfig {

    @Bean
    @Primary
    public DataSource dataSource() {
        return new EmbeddedDatabaseBuilder()
            .generateUniqueName(true)
            .setType(H2)
            .setScriptEncoding("UTF-8")
            .ignoreFailedDrops(true)
            .addScript("schema.sql")
            .addScripts("user_data.sql", "country_data.sql")
            .build();
    }
}