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

标签 java spring junit spring-boot spring-test

情况:

  1. 我在微服务中使用 Spring CloudSpring Boot,该微服务正在加载数据库配置信息以配置连接。
  2. 我创建了一个测试来使用 Swagger 获取其余接口(interface)作为文档。
  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 注释。

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

关于java - 如何在 Spring Boot 中模拟数据库连接以进行测试?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35707469/

相关文章:

java - 我正在尝试为插入时间表的方法编写一个 JUnit 测试用例,该时间表将参数作为员工 ID。我应该如何尝试?

java - "java: package org.apache.cordova does not exist"在Android Studio中编译Cordova时

java - 如何使用JSoup通过发送特定日期来获取网页?

c# - 单元测试组织

java - 如果在后台运行的 Spring Batch 作业将更新 sql 结果状态,如何更新 jsp 状态(从提交到处理然后成功)

java - Spring JMS 监听器未连接到 ActiveMQ

java - Spring hibernate java.sql.SQLException : The result set is closed

java - java中的getters应该有验证吗?

Java 字节数组到字符串到字节数组

java - 我们可以使用junit编写功能测试吗?