【问题标题】:How can I mock db connection in Spring Boot for testing purpose?如何在 Spring Boot 中模拟数据库连接以进行测试?
【发布时间】:2016-06-12 23:01:40
【问题描述】:

情况:

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

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

【问题讨论】:

  • 模拟你的服务层。就这么简单。

标签: java spring junit spring-boot spring-test


【解决方案1】:

有一个选项可以使用简单的 Spring 特性来伪造 Spring bean。你需要为它使用@Primary@Profile@ActiveProfiles注解。

I wrote a blog post on the topic.

您可以使用内存数据库(例如 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();
    }
}

【讨论】:

  • 来自博客:从 Spring Boot 1.4.0 开始,通过注解 @MockBean 原生支持伪造 Spring Beans。阅读Spring Boot docs 了解更多信息。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-12-12
  • 1970-01-01
  • 1970-01-01
  • 2020-07-23
  • 1970-01-01
  • 2019-01-30
  • 1970-01-01
相关资源
最近更新 更多