单元测试中的 Spring Boot 数据源 [英] Spring Boot Datasource in unit tests

查看:128
本文介绍了单元测试中的 Spring Boot 数据源的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的 Spring Boot Web 应用程序,它从数据库中读取数据并返回一个 JSON 响应.我有以下测试配置:

I have a simple Spring Boot web app, that reads from a database and return a JSON response. I have the following test configuration:

@RunWith(SpringRunner.class)
@SpringBootTest(classes=MyApplication.class, properties={"spring.config.name=myapp"})
@AutoConfigureMockMvc
public class ControllerTests {
    @Autowired
    private MockMvc mvc;
    @MockBean
    private ProductRepository productRepo;
    @MockBean
    private MonitorRepository monitorRepo;

    @Before
    public void setupMock() {
        Mockito.when(productRepo.findProducts(anyString(), anyString()))
        .thenReturn(Arrays.asList(dummyProduct()));     
    }

    @Test
    public void expectBadRequestWhenNoParamters() throws Exception {    
        mvc.perform(get("/products"))
                .andExpect(status().is(400))
                .andExpect(jsonPath("$.advice.status", is("ERROR")));
    }

    //other tests
}

我在应用程序的主配置中配置了一个 DataSource bean.当我运行测试时,Spring 尝试加载上下文并失败,因为数据源来自 JNDI.一般来说,我想避免为此测试创建数据源,因为我模拟了存储库.

I have a DataSource bean that is configured in the main configuration of the application. When I run the tests Spring tries to load the context and fails, because the datasource is taken from JNDI. In general I want to avoid creating a datasource for this tests, because I have the repositories mocked.

运行单元测试时是否可以跳过数据源的创建?

Is it possible to skip the creation of datasource when running the unit tests?

用于测试的内存数据库不是一个选项,因为我的数据库创建脚本具有特定的结构并且无法从 classpath:schema.sql 轻松执行

In memory database for testing is not an option, because my database creation script has a specific structure and cannot be easily executed from classpath:schema.sql

编辑数据源定义在 MyApplication.class

    @Bean
    DataSource dataSource(DatabaseProeprties databaseProps) throws NamingException {
       DataSource dataSource = null;
       JndiTemplate jndi = new JndiTemplate();
       setJndiEnvironment(databaseProps, jndi);
       try {
           dataSource = jndi.lookup(databaseProps.getName(), DataSource.class);
       } catch (NamingException e) {
           logger.error("Exception loading JNDI datasource", e);
           throw e;
       }
       return dataSource;
   }

推荐答案

由于您正在加载配置类 MyApplication.class 数据源 bean 将被创建,请尝试将数据源移动到另一个未使用的 bean 中一个测试,确保为测试加载的所有类不依赖于数据源.
或者
在你的测试中创建一个用 @TestConfiguration 标记的配置类并将其包含在 SpringBootTest(classes=TestConfig.class) 在那里模拟数据源,如

Since you are loading configuration class MyApplication.class datasource bean will be created, Try moving datasource in another bean which is not used in a test, make sure all classes loaded for tests are not dependant on datasource.
Or
In your tests create a config class marked with @TestConfiguration and include it in SpringBootTest(classes=TestConfig.class) mocking data source there like

@Bean
public DataSource dataSource() {
    return Mockito.mock(DataSource.class);
}

但这可能会失败,因为调用此模拟数据源进行连接的方法将返回 null,在这种情况下,您必须创建一个内存中数据源,然后模拟 jdbcTemplate 和其余依赖项.

But this may fail since method call to this mocked datasouce for connection will return null, In that case, you'll have to create an in-memory datasource and then mock jdbcTemplate and rest of dependencies.

这篇关于单元测试中的 Spring Boot 数据源的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆