我有一个简单的 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 中,确保为测试加载的所有类都不依赖于datasource.
或
在你的测试中创建一个配置类标记为 @TestConfiguration
并将其包含在 SpringBootTest(classes=TestConfig.class)
模拟数据中源那里像
@Bean
public DataSource dataSource() {
return Mockito.mock(DataSource.class);
}
但这可能会失败,因为调用此模拟数据源进行连接的方法将返回 null,在这种情况下,您必须创建一个内存中数据源,然后模拟 jdbcTemplate 和其余依赖项。
关于java - 单元测试中的 Spring Boot 数据源,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49559185/