【发布时间】:2016-05-15 01:50:09
【问题描述】:
我正在尝试使用 spring 测试来测试 rest 应用程序。
我有两个实体(用户、用户信息) (假设源和目标共享相同的主键值的一对一关联。)
这是我的测试场景。 (在测试代码中)
- 使用 JPA 将临时用户插入数据库
- 请求控制器使用 MockMvc 执行。
- 根据预期和实际进行断言。
- 回滚临时用户。
此测试用例失败。 也许到另一个执行环境(线程)??
@Test
public void test() throws Exception {
// create temporary user for test.
User user = new User();
user.setType(Type.User);
UserInfo userInfo = new UserInfo();
userInfo.setEmail("temporary_user@test.com");
userInfo.setUser(user);
user.setUserInfo(userInfo);
// persist
userRepository.save(user);
// request post
mockMvc.perform(
post("/user")
.param("email", "temporary_user@test.com")
.contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
.andExpect(status().isOk())
.andExpect(jsonPath("$.email", userInfo.getEmail()));
}
有可能的测试场景吗??
对其他解决方案或如何让我的解决方案发挥作用有任何帮助吗?
这是一个示例代码。
https://gist.github.com/okihouse/f5e2fe8fa4c17d6a6be9
已解决
我解决了这个异常。
异常点
-
我使用了 hikariCP。观看示例代码。
@Configuration @EnableAutoConfiguration @EnableTransactionManagement public class JdbcConfig implements TransactionManagementConfigurer { @Autowired private JdbcVO jdbcVO; @Bean public JdbcTemplate jdbcTemplate(){ return new JdbcTemplate(dataSource()); } @Bean public DataSource dataSource(){ final HikariDataSource dataSource = new HikariDataSource(); dataSource.setDriverClassName(jdbcVO.getDriver()); dataSource.setJdbcUrl(jdbcVO.getUrl()); dataSource.setUsername(jdbcVO.getUsername()); dataSource.setPassword(jdbcVO.getPassword()); return dataSource; } @Bean public PlatformTransactionManager transactionManager(){ return new DataSourceTransactionManager(dataSource()); } @Override public PlatformTransactionManager annotationDrivenTransactionManager() { return transactionManager(); }}
当我使用手动数据源配置时发生错误。
所以,我在 application.yml
中更新数据源配置spring:
jpa:
database: mysql
hibernate:
naming-strategy: org.hibernate.cfg.ImprovedNamingStrategy
#ddl-auto: create
properties:
hibernate.format_sql: true
show-sql: true
datasource:
type: com.zaxxer.hikari.HikariDataSource
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://localhost:3306/test
username: test
password: test
最后,我分享了这段代码。 https://github.com/okihouse/spring-jpa-test
【问题讨论】:
-
是的,这种测试是可能的。你得到了什么 ?一个例外?你的测试用例中没有断言
-
我想说不是真的,因为如果你使用“独立”mockmvc,就没有真正的 spring 上下文(没有数据源等),如果你使用另一个(有上下文的那个),你通常无法访问存储库/数据层。但是可以将模拟与独立的 mockmvc 一起使用,并将一个固定的数据库(在内存中,预定义的数据)与另一个一起使用。另见stackoverflow.com/questions/32223490/…
-
Jérémie B 是正确的,这种测试有效,只要去做,不要忘记测试时的@Transactional 注释。
标签: java spring jpa transactional mockmvc