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

@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.一般情况下,我想避免为此测试创建数据源,因为我已经模拟了存储库.

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

在内存数据库中进行测试不是一个选项,因为我的数据库创建脚本具有特定的结构,并且无法从类路径中轻松执行: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)中,模拟数据源就像那样

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

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

点击查看更多相关文章

转载注明原文:java – 单元测试中的Spring Boot Datasource - 乐贴网