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


情况:

  1. 我在用 Spring Cloud 同 Spring 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());
    }
}

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


12074
2018-02-29 19:03


起源

模拟你的服务层。就那么简单。 - Branislav Lazic


答案:


有一个选项可以使用简单的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();
    }
}

13
2018-02-29 20:17