首页 文章

单元测试中的Spring Boot数据源

提问于
浏览
4

我有一个简单的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

Edit 数据源在 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;
   }

2 回答

  • 6

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

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

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

  • 1

    尝试将您的数据源添加为@MockBean

    @MockBean
    private DataSource dataSource
    

    这样Spring将为您做替换逻辑,具有甚至不会执行 生产环境 代码bean创建(没有JNDI查找)的优势 .

相关问题