작성
·
932
1
2022-12-11 20:07:11.120 INFO 5728 --- [ main] o.s.t.c.transaction.TransactionContext : Began transaction (1) for test context [DefaultTestContext@7e8dcdaa testClass = MemberServiceIntegrationTest, testInstance = hello.hellospring.service.MemberServiceIntegrationTest@236ae13d, testMethod = 중복_회원_예외@MemberServiceIntegrationTest, testException = [null], mergedContextConfiguration = [WebMergedContextConfiguration@681a8b4e testClass = MemberServiceIntegrationTest, locations = '{}', classes = '{class hello.hellospring.HelloSpringApplication}', contextInitializerClasses = '[]', activeProfiles = '{}', propertySourceLocations = '{}', propertySourceProperties = '{org.springframework.boot.test.context.SpringBootTestContextBootstrapper=true}', contextCustomizers = set[org.springframework.boot.test.autoconfigure.actuate.metrics.MetricsExportContextCustomizerFactory$DisableMetricExportContextCustomizer@20bd8be5, org.springframework.boot.test.autoconfigure.properties.PropertyMappingContextCustomizer@0, org.springframework.boot.test.autoconfigure.web.servlet.WebDriverContextCustomizerFactory$Customizer@4a07d605, org.springframework.boot.test.context.filter.ExcludeFilterContextCustomizer@68746f22, org.springframework.boot.test.json.DuplicateJsonObjectContextCustomizerFactory$DuplicateJsonObjectContextCustomizer@2eea88a1, org.springframework.boot.test.mock.mockito.MockitoContextCustomizer@0, org.springframework.boot.test.web.client.TestRestTemplateContextCustomizer@7283d3eb, org.springframework.boot.test.context.SpringBootTestArgs@1, org.springframework.boot.test.context.SpringBootTestWebEnvironment@130f889], resourceBasePath = 'src/main/webapp', contextLoader = 'org.springframework.boot.test.context.SpringBootContextLoader', parent = [null]], attributes = map['org.springframework.test.context.web.ServletTestExecutionListener.activateListener' -> true, 'org.springframework.test.context.web.ServletTestExecutionListener.populatedRequestContextHolder' -> true, 'org.springframework.test.context.web.ServletTestExecutionListener.resetRequestContextHolder' -> true, 'org.springframework.test.context.event.ApplicationEventsTestExecutionListener.recordApplicationEvents' -> false]]; transaction manager [org.springframework.jdbc.support.JdbcTransactionManager@193eb1ba]; rollback [true]
2022-12-11 20:07:11.845 INFO 5728 --- [ main] o.s.t.c.transaction.TransactionContext : Rolled back transaction for test: [DefaultTestContext@7e8dcdaa testClass = MemberServiceIntegrationTest, testInstance = hello.hellospring.service.MemberServiceIntegrationTest@236ae13d, testMethod = 중복_회원_예외@MemberServiceIntegrationTest, testException = org.opentest4j.AssertionFailedError: Expected java.lang.IllegalStateException to be thrown, but nothing was thrown., mergedContextConfiguration = [WebMergedContextConfiguration@681a8b4e testClass = MemberServiceIntegrationTest, locations = '{}', classes = '{class hello.hellospring.HelloSpringApplication}', contextInitializerClasses = '[]', activeProfiles = '{}', propertySourceLocations = '{}', propertySourceProperties = '{org.springframework.boot.test.context.SpringBootTestContextBootstrapper=true}', contextCustomizers = set[org.springframework.boot.test.autoconfigure.actuate.metrics.MetricsExportContextCustomizerFactory$DisableMetricExportContextCustomizer@20bd8be5, org.springframework.boot.test.autoconfigure.properties.PropertyMappingContextCustomizer@0, org.springframework.boot.test.autoconfigure.web.servlet.WebDriverContextCustomizerFactory$Customizer@4a07d605, org.springframework.boot.test.context.filter.ExcludeFilterContextCustomizer@68746f22, org.springframework.boot.test.json.DuplicateJsonObjectContextCustomizerFactory$DuplicateJsonObjectContextCustomizer@2eea88a1, org.springframework.boot.test.mock.mockito.MockitoContextCustomizer@0, org.springframework.boot.test.web.client.TestRestTemplateContextCustomizer@7283d3eb, org.springframework.boot.test.context.SpringBootTestArgs@1, org.springframework.boot.test.context.SpringBootTestWebEnvironment@130f889], resourceBasePath = 'src/main/webapp', contextLoader = 'org.springframework.boot.test.context.SpringBootContextLoader', parent = [null]], attributes = map['org.springframework.test.context.web.ServletTestExecutionListener.activateListener' -> true, 'org.springframework.test.context.web.ServletTestExecutionListener.populatedRequestContextHolder' -> true, 'org.springframework.test.context.web.ServletTestExecutionListener.resetRequestContextHolder' -> true, 'org.springframework.test.context.event.ApplicationEventsTestExecutionListener.recordApplicationEvents' -> false]]
org.opentest4j.AssertionFailedError: Expected java.lang.IllegalStateException to be thrown, but nothing was thrown
라는 오류가 나옵니다
package hello.hellospring.service;
import hello.hellospring.domain.Member;
import hello.hellospring.repository.MemberRepository;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.transaction.annotation.Transactional;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
@SpringBootTest
@Transactional
class MemberServiceIntegrationTest {
@Autowired MemberService memberService;
@Autowired MemberRepository memberRepository;
@Test
public void 회원가입() throws Exception {
//Given
Member member = new Member();
member.setName("hello");
//When
Long saveId = memberService.join(member);
//Then
Member findMember = memberRepository.findById(saveId).get();
assertEquals(member.getName(), findMember.getName());
}
@Test
public void 중복_회원_예외() throws Exception {
//Given
Member member1 = new Member();
member1.setName("spring");
Member member2 = new Member();
member2.setName("spring");
//When
memberService.join(member1);
IllegalStateException e = assertThrows(IllegalStateException.class,
() -> memberService.join(member2));//예외가 발생해야 한다.
assertThat(e.getMessage()).isEqualTo("이미 존재하는 회원입니다.");
}
}
package hello.hellospring.service;
import hello.hellospring.domain.Member;
import hello.hellospring.repository.MemberRepository;
import java.util.List;
import java.util.Optional;
public class MemberService {
private final MemberRepository memberRepository;
public MemberService(MemberRepository memberRepository) {
this.memberRepository = memberRepository;
}
/**
* 회원가입
*/
public Long join (Member member){
validateDuplicateMember(member); //중복 회원 검증
memberRepository.save(member);
return member.getId();
}
private void validateDuplicateMember (Member member){
memberRepository.findByName(member.getName())
.ifPresent(m -> {
throw new IllegalStateException("이미 존재하는 회원입니다.");
});
}
/**
* 전체 회원 조회
*/
public List<Member> findMembers () {
return memberRepository.findAll();
}
public Optional<Member> findOne (Long memberId){
return memberRepository.findById(memberId);
}
}
일단 memberserviceTest도 돌려서 확인했을때 중복 회원 예외에 대한 문제는 나오지를 않았습니다.
다른 질문들 확인했을때 메세지 뜨는게 달라서 안뜬다고 해서 그 메세지 자체 그대로 복붙했습니다. 에러에서는 그런게 보이지도 않았구요
db에 문제가 있는건가 싶어서 테이블 자체를 없앴다가 다시만들고 테스트 당시 db에 spring1이라는 이름의 데이터 한개 있습니다.
이 테스트 자체가 member1이랑 member2랑 이름이 같아서 중복 회원 오류를 테스트 하는거라서 spring이라는 이름으로 겹치지 않게 할려고 일부로 데이터도 spring1으로 해놨습니다.
어떤 문제때문에 지금 계속 저 오류가 뜨는건지 질문드립니다.
답변 2
1
h2콘솔에서 insert문 사용해서 spring1 이라는 데이터는 넣었구요
member에서 혹시나 문제가 있을까 해서 복붙해서 다시 돌려봤는데도 문제가 생겨서
https://drive.google.com/file/d/1wt0Y-MlXNSkpv_0OLpPEkEaeFnjK3nmV/view?usp=share_link
구글 폼으로 질문 드립니다. 확인 부탁드립니다.
0
IllegalStateException to be thrown, but nothing was thrown
이 메시지는 해당 예외가 발생할 것이라고 정의해놓았지만 발생하지 않아서 출력되는 메시지입니다.
그럼 예외가 발생하지 않았는지를 확인해봐야할텐데요.
memberRepository.findByName(member.getName())
.ifPresent(m -> {
throw new IllegalStateException("이미 존재하는 회원입니다.");
});
ifPresent 즉, 회원저장소에서 이름으로 조회했을 때 존재할 경우 예외가 발생하지만 존재하지 않는 이유에 대해 확인해볼 필요가 있습니다.
회원 데이터 spring1이 존재한다고 하였는데, h2의 콘솔에서 직접 데이터를 Insert 한게 아니라면 애플리케이션에서 실행되어 저장이 된 데이터 일 것 같은데요.
memberRepository의 save와 member의 setName은 문제가 없을 것으로 예상이 되고 member의 getName()이 제대로 동작하지 않나 예상 할 수 있을 것 같습니다.
Member클래스를 확인해보시고 특이점이 안보일 경우 댓글남겨주세요
.
감사합니다.
getName이 아니라 JdbcTemplateMemberRepository.findByName()이 강의와 다르네요 ^^
findByName코드 구현 코드를 추가해주세요