/// 테스트 코드
@Test
public void doVoteTest(){
Restaurant restaurant1 = Restaurant.builder().name("abc").restaurantHash("13").build();
Restaurant restaurant2 = Restaurant.builder().name("def").restaurantHash("12").build();
restaurantRepository.save(restaurant1);
restaurantRepository.save(restaurant2);
..... (중략)
List<String> options = new ArrayList<>();
options.add("13");
CreateVoteResultRequest createVoteResultRequest = new CreateVoteResultRequest();
createVoteResultRequest.setUserId(voter1.getId());
createVoteResultRequest.setNickname("123");
createVoteResultRequest.setOptions(options);
/// 테스트 하는 부분
voteService.createVoteResult(voteOption1.getVote().getVoteHash() , createVoteResultRequest);
}
/// 서비스 레이어 코드
public void createVoteResult(String voteHash, CreateVoteResultRequest createVoteResultRequest) {
Long userId = createVoteResultRequest.getUserId();
List<String> options = createVoteResultRequest.getOptions();
Vote vote = checkVoteExists(voteHash);
Voter voter = checkVoterExists(voteHash, userId);
checkUserVoted(vote, userId);
checkDuplicated(vote, options);
List<VoteResult> voteResults = new ArrayList<>();
options.forEach(option -> {
vote.getVoteOptions().forEach(voteOption -> {
if (Objects.equals(voteOption.getRestaurant().getRestaurantHash(), option)) {
VoteResult voteResult = VoteResult.builder()
.voter(voter)
.voteOption(voteOption)
.build();
voteResults.add(voteResult);
}
});
});
voteResultRepository.saveAll(voteResults);
}
@Transactional 어노테이션이 존재하지 않는다. 그래서 나는 당연히 LazyInitializationException 이 발생할 줄 알았다.Spring Boot 를 이용한 application 의 경우, 디폴트로 osiv 가 true 로 설정되어있다. 그래서 Service layer 에서 @Transactional 어노테이션이 없어도 lazy loading 이 가능했다.
하지만 테스트코드에는 OSIV 가 적용되지 않는다. 따라서 해당 테스트코드가 같은 영속성 컨텍스트를 공유하게 하려면 @Transactional 어노테이션을 붙이면 된다.