繁体   English   中英

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

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

情况:

  1. 我在微服务中使用Spring CloudSpring Boot ,微服务正在加载数据库配置信息以配置连接。
  2. 我创建了一个测试,以使用Swagger获取其余接口以获取文档。
  3. 我想禁用数据库配置的加载,因为没有必要。

这是代码:

@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());
    }
}

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

有一个选项可以使用简单的Spring功能来伪造Spring bean。 您需要使用@Primary@Profile@ActiveProfiles注解吧。

我写了一篇关于这个主题的博客文章。

您可以在内存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();
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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