【发布时间】:2018-09-08 14:17:31
【问题描述】:
我有一个简单的 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。一般来说,我想避免为此测试创建数据源,因为我已经模拟了存储库。
运行单元测试时是否可以跳过数据源的创建?
在内存数据库中进行测试不是一个选项,因为我的数据库创建脚本具有特定的结构,无法从 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;
}
【问题讨论】:
-
您的数据源是否通过自动配置进行配置?
-
@wjans 不,它是主配置中的一个 bean。查看我的编辑。
-
你不能简单地将数据源添加为
@MockBean DataSource dataSource吗?认为它的优点是您的生产代码执行 JNDI 查找甚至不会被执行。
标签: java spring unit-testing spring-boot mockito