I'm try testing rest application using spring test.
I have two entity (User, UserInfo) (One-to-one association that assumes both the source and target share the same primary key values.)
This is my testing scenario. (in test code)
- Insert temporary user to database using JPA
- Request controller using MockMvc perform.
- Assert with expected and actual.
- Rollback temporary user.
This test case is failed. perhaps to another execution environment(thread) ??
@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()));
}
Is it possible test scenario??
Any help on another solution or how to get my solution working?
This is a sample code.
https://gist.github.com/okihouse/f5e2fe8fa4c17d6a6be9
Solved
I solved this exception.
exception point
I used hikariCP. watch sample code.
@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(); }
}
Error occured when I used manually datasource configuration.
So, I update datasource configuration in 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
Finally, I shared this code. https://github.com/okihouse/spring-jpa-test