0
我嘗試使用彈簧測試測試其餘應用程序。是否可以通過MockMvc進行JPA測試?
我有兩個實體(用戶,的UserInfo) (一對一的關聯,它假定在源和目標都共享相同的主鍵值。)
這是我的測試場景。 (測試代碼)使用利用MockMvc執行JPA
- 插入臨時用戶數據庫。
- 斷言與預期和實際。
- 回滾臨時用戶。
該測試用例失敗。 也許到另一個執行環境(線程)?
@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("[email protected]");
userInfo.setUser(user);
user.setUserInfo(userInfo);
// persist
userRepository.save(user);
// request post
mockMvc.perform(
post("/user")
.param("email", "[email protected]")
.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
是,這種測試是可能的。你得到了什麼 ?一個例外?你在測試用例中沒有斷言 –
我不會說真的,因爲如果你使用「standalone」mockmvc,沒有真正的spring context(沒有數據源等),並且如果你使用另一個(帶有上下文的),你通常無法訪問存儲庫/數據層。但是可以將mock與獨立的mockmvc一起使用,並使用另一個固定的DB(在內存中,預定義的數據)。另請參閱http://stackoverflow.com/questions/32223490/are-springs-mockmvc-used-for-unit-testing-or-integration-testing – 2016-02-05 07:12:29
JérémieB是可靠的,這種測試工作,只是做到了,而且在測試中不要忘記@Transactional註釋。 – Ralph