밑에 질문했던 점프 투 스프링부트 2-05에서 답변에 연결된 질문 찾기 vs 질문에 달린 답변 찾기관련 오류에 대해서 궁금한 점이 또 있습니다.
답변에는 Member 엔티티에 관련된 부분도 작성해주셔야 된다고 하셨는데 앞서 다른 테스트 코드는 Member 엔티티에 관련된 부분을 작성하지 않아도 통과가 되었습니다.
우선 Question, Answer, 테스트코드 순서로 차례대로 코드를 달겠습니다.
Question 엔티티
@Entity
@Getter @Setter
public class Question {
@Id @GeneratedValue
@Column(name = "question_id")
private Long id;
@Column(unique = true, length = 200)
private String subject;
@Column(unique = true, columnDefinition = "TEXT")
private String content;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "member_id")
private Member member;
@OneToMany(mappedBy = "question", cascade = CascadeType.REMOVE)
private List<Answer> answerList;
private LocalDateTime createDate;
}
Answer 엔티티
@Entity
@Getter @Setter
public class Answer {
@Id @GeneratedValue
@Column(name = "answer_id")
private Long id;
@Column(columnDefinition = "TEXT")
private String content;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "member_id")
private Member member;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "question_id")
private Question question;
private LocalDateTime createDate;
}
테스트 코드 - 답변조회 메서드는 실행이 잘됩니다, 질문조회 메서드만 오류가 나는 상태입니다.
@SpringBootTest
@Transactional
class AnswerRepositoryTest {
@Autowired
private QuestionRepository questionRepository;
@Autowired
private AnswerRepository answerRepository;
@Test
public void 답변조회() throws Exception{
//given
Question q = new Question();
q.setSubject("제목입니다.");
q.setContent("본문입니다.");
Question savedQuestion = questionRepository.save(q);
Answer a = new Answer();
a.setContent("답변입니다.");
a.setCreateDate(LocalDateTime.now());
a.setQuestion(questionRepository.findById(savedQuestion.getId()).get());
Answer savedAnswer = answerRepository.save(a);
//when
Answer findByIdAnswer = answerRepository.findById(savedAnswer.getId()).get();
//then
assertEquals(findByIdAnswer.getQuestion(),savedQuestion);
}
@Test
public void 질문조회() throws Exception{
//given
Question q = new Question();
q.setSubject("제목입니다.");
q.setContent("본문입니다.");
Question saveQuestion = questionRepository.save(q);
Question question = questionRepository.findById(saveQuestion.getId()).get();
Answer a = new Answer();
a.setContent("답변입니다.");
a.setQuestion(question);
a.setCreateDate(LocalDateTime.now());
answerRepository.save(a);
//when
List<Answer> answerList = question.getAnswerList();
//then
assertEquals(1,answerList.size());
assertEquals("답변입니다.",answerList.get(0).getContent());
}
}
여기 오류 코드입니다.
wlghsms95 님 412
M 2023년 2월 22일 2:34 오후
댓글 1개 더 보기...
@박응용님 메서드에 @Transactional을 추가해도 똑같이 안돼요... 그리고 제가 이것저것 다르게 해보면서 봤는데
answerList에 자꾸 아무 값도 안 들어간 상태가 되어서 null로 뜨더라고요 출력이든 검증이든 answerList만 가지고 뭘 하려고 하면 똑같은 오류가 나요
혹시나 몰라서 오류 트레이스도 첨부하겠습니다.
2023-02-22 17:29:08.274 INFO 10928 --- [ main] o.s.t.c.transaction.TransactionContext : Began transaction (1) for test context [DefaultTestContext@14dda234 testClass = AnswerRepositoryTest, testInstance = springproject.board.repository.AnswerRepositoryTest@4ac26092, testMethod = 답변전체조회@AnswerRepositoryTest, testException = [null], mergedContextConfiguration = [WebMergedContextConfiguration@3f390d63 testClass = AnswerRepositoryTest, locations = '{}', classes = '{class springproject.board.BoardApplication}', contextInitializerClasses = '[]', activeProfiles = '{}', propertySourceLocations = '{}', propertySourceProperties = '{org.springframework.boot.test.context.SpringBootTestContextBootstrapper=true}', contextCustomizers = set[org.springframework.boot.test.autoconfigure.actuate.metrics.MetricsExportContextCustomizerFactory$DisableMetricExportContextCustomizer@19b843ba, org.springframework.boot.test.autoconfigure.properties.PropertyMappingContextCustomizer@0, org.springframework.boot.test.autoconfigure.web.servlet.WebDriverContextCustomizerFactory$Customizer@2415fc55, org.springframework.boot.test.context.filter.ExcludeFilterContextCustomizer@cd1e646, org.springframework.boot.test.json.DuplicateJsonObjectContextCustomizerFactory$DuplicateJsonObjectContextCustomizer@2bec854f, org.springframework.boot.test.mock.mockito.MockitoContextCustomizer@0, org.springframework.boot.test.web.client.TestRestTemplateContextCustomizer@23202fce, org.springframework.boot.test.context.SpringBootTestArgs@1, org.springframework.boot.test.context.SpringBootTestWebEnvironment@1c72da34], 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.orm.jpa.JpaTransactionManager@13976c57]; rollback [true]
2023-02-22 17:29:08.468 INFO 10928 --- [ main] o.s.t.c.transaction.TransactionContext : Rolled back transaction for test: [DefaultTestContext@14dda234 testClass = AnswerRepositoryTest, testInstance = springproject.board.repository.AnswerRepositoryTest@4ac26092, testMethod = 답변전체조회@AnswerRepositoryTest, testException = java.lang.NullPointerException, mergedContextConfiguration = [WebMergedContextConfiguration@3f390d63 testClass = AnswerRepositoryTest, locations = '{}', classes = '{class springproject.board.BoardApplication}', contextInitializerClasses = '[]', activeProfiles = '{}', propertySourceLocations = '{}', propertySourceProperties = '{org.springframework.boot.test.context.SpringBootTestContextBootstrapper=true}', contextCustomizers = set[org.springframework.boot.test.autoconfigure.actuate.metrics.MetricsExportContextCustomizerFactory$DisableMetricExportContextCustomizer@19b843ba, org.springframework.boot.test.autoconfigure.properties.PropertyMappingContextCustomizer@0, org.springframework.boot.test.autoconfigure.web.servlet.WebDriverContextCustomizerFactory$Customizer@2415fc55, org.springframework.boot.test.context.filter.ExcludeFilterContextCustomizer@cd1e646, org.springframework.boot.test.json.DuplicateJsonObjectContextCustomizerFactory$DuplicateJsonObjectContextCustomizer@2bec854f, org.springframework.boot.test.mock.mockito.MockitoContextCustomizer@0, org.springframework.boot.test.web.client.TestRestTemplateContextCustomizer@23202fce, org.springframework.boot.test.context.SpringBootTestArgs@1, org.springframework.boot.test.context.SpringBootTestWebEnvironment@1c72da34], 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]]
java.lang.NullPointerException
at springproject.board.repository.AnswerRepositoryTest.답변전체조회(AnswerRepositoryTest.java:73)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:566)
at org.junit.platform.commons.util.ReflectionUtils.invokeMethod(ReflectionUtils.java:725)
at org.junit.jupiter.engine.execution.MethodInvocation.proceed(MethodInvocation.java:60)
at org.junit.jupiter.engine.execution.InvocationInterceptorChain$ValidatingInvocation.proceed(InvocationInterceptorChain.java:131)
at org.junit.jupiter.engine.extension.TimeoutExtension.intercept(TimeoutExtension.java:149)
at org.junit.jupiter.engine.extension.TimeoutExtension.interceptTestableMethod(TimeoutExtension.java:140)
at org.junit.jupiter.engine.extension.TimeoutExtension.interceptTestMethod(TimeoutExtension.java:84)
at org.junit.jupiter.engine.execution.ExecutableInvoker$ReflectiveInterceptorCall.lambda$ofVoidMethod$0(ExecutableInvoker.java:115)
at org.junit.jupiter.engine.execution.ExecutableInvoker.lambda$invoke$0(ExecutableInvoker.java:105)
at org.junit.jupiter.engine.execution.InvocationInterceptorChain$InterceptedInvocation.proceed(InvocationInterceptorChain.java:106)
at org.junit.jupiter.engine.execution.InvocationInterceptorChain.proceed(InvocationInterceptorChain.java:64)
at org.junit.jupiter.engine.execution.InvocationInterceptorChain.chainAndInvoke(InvocationInterceptorChain.java:45)
at org.junit.jupiter.engine.execution.InvocationInterceptorChain.invoke(InvocationInterceptorChain.java:37)
at org.junit.jupiter.engine.execution.ExecutableInvoker.invoke(ExecutableInvoker.java:104)
at org.junit.jupiter.engine.execution.ExecutableInvoker.invoke(ExecutableInvoker.java:98)
at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.lambda$invokeTestMethod$7(TestMethodTestDescriptor.java:214)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.invokeTestMethod(TestMethodTestDescriptor.java:210)
at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:135)
at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:66)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$6(NodeTestTask.java:151)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:141)
at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:137)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$9(NodeTestTask.java:139)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:138)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:95)
at java.base/java.util.ArrayList.forEach(ArrayList.java:1541)
at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:41)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$6(NodeTestTask.java:155)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:141)
at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:137)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$9(NodeTestTask.java:139)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:138)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:95)
at java.base/java.util.ArrayList.forEach(ArrayList.java:1541)
at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:41)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$6(NodeTestTask.java:155)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:141)
at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:137)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$9(NodeTestTask.java:139)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:138)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:95)
at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.submit(SameThreadHierarchicalTestExecutorService.java:35)
at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor.execute(HierarchicalTestExecutor.java:57)
at org.junit.platform.engine.support.hierarchical.HierarchicalTestEngine.execute(HierarchicalTestEngine.java:54)
at org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:107)
at org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:88)
at org.junit.platform.launcher.core.EngineExecutionOrchestrator.lambda$execute$0(EngineExecutionOrchestrator.java:54)
at org.junit.platform.launcher.core.EngineExecutionOrchestrator.withInterceptedStreams(EngineExecutionOrchestrator.java:67)
at org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:52)
at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:114)
at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:86)
at org.junit.platform.launcher.core.DefaultLauncherSession$DelegatingLauncher.execute(DefaultLauncherSession.java:86)
at org.junit.platform.launcher.core.SessionPerRequestLauncher.execute(SessionPerRequestLauncher.java:53)
at com.intellij.junit5.JUnit5IdeaTestRunner.startRunnerWithArgs(JUnit5IdeaTestRunner.java:57)
at com.intellij.rt.junit.IdeaTestRunner$Repeater$1.execute(IdeaTestRunner.java:38)
at com.intellij.rt.execution.junit.TestsRepeater.repeat(TestsRepeater.java:11)
at com.intellij.rt.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:35)
at com.intellij.rt.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:235)
at com.intellij.rt.junit.JUnitStarter.main(JUnitStarter.java:54)
-
wlghsms95님,
2023년 2월 22일 5:33 오후
추천
,
대댓글
@wlghsms95님 Question question = questionRepository.findById(saveQuestion.getId()).get(); 문장을 답변 저장한 후로 위치를 바꾸고 해보세요. 제가 현재 테스트할수 있는 환경이 아니라서 확인은 못해 봤습니다.
-
박응용님,
2023년 2월 22일 5:41 오후
추천
,
대댓글

@박응용님 답변 감사드립니다! 하지만 위의 방법도 되질 않네요...제가 한번 다른 방법으로 다시 해보겠습니다!!! 답변 친절하게 달아주셔서 너무 감사합니다!!!
-
wlghsms95님,
2023년 2월 23일 12:05 오전
추천
,
대댓글
@wlghsms95님 save 메서드 대신 saveAndFlush 도 한번 사용해 보세요. fetchType이 Lazy 모드라 insert문이 실행되기 전에 조회가 되는 것 같습니다.
-
박응용님,
2023년 2월 23일 12:37 오전
추천
,
대댓글

@박응용님 그것도 안되네요...도움 정말 감사드립니다. 제가 한번 다른 부분들이나 설정들을 뜯어고쳐서 다시 해보도록 하겠습니다 감사합니다!!
-
wlghsms95님,
2023년 2월 23일 1:25 오전
추천
,
대댓글