Skip to content

Commit 4ac170f

Browse files
committed
Rewrite testCreate with capturedQuestion
1 parent 62f5148 commit 4ac170f

File tree

1 file changed

+10
-4
lines changed

1 file changed

+10
-4
lines changed

src/test/java/com/example/postgresdemo/service/QuestionServiceTest.java

Lines changed: 10 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,9 @@ class QuestionServiceTest {
2929
@InjectMocks
3030
QuestionService questionService;
3131

32+
@Captor
33+
ArgumentCaptor<Question> questionCaptor;
34+
3235
@Test
3336
void testFindAll() {
3437
Question question1 = new Question();
@@ -62,12 +65,16 @@ void testCreate() {
6265
question.setId(1L);
6366
question.setTitle("Title");
6467
question.setDescription("Description");
65-
Mockito.when(questionRepository.save(any(Question.class))).thenReturn(question);
68+
Mockito.when(questionRepository.save(questionCaptor.capture())).thenReturn(question);
6669

6770
QuestionResponseDTO result = questionService.create(request);
6871

69-
Mockito.verify(questionRepository).save(any(Question.class));
70-
Assertions.assertEquals("Title\nDescription", result.getBody());
72+
Mockito.verify(questionRepository).save(questionCaptor.capture());
73+
74+
Question capturedQuestion = questionCaptor.getValue();
75+
76+
Assertions.assertEquals(request.getTitle(), capturedQuestion.getTitle());
77+
Assertions.assertEquals(request.getDescription(), capturedQuestion.getDescription());
7178
Assertions.assertEquals(1L, result.getId());
7279
}
7380

@@ -82,7 +89,6 @@ void testUpdateExistingQuestion() {
8289
questionToUpdate.setTitle("Old Title");
8390
questionToUpdate.setDescription("Old Description");
8491

85-
ArgumentCaptor<Question> questionCaptor = ArgumentCaptor.forClass(Question.class);
8692
Mockito.when(questionRepository.findById(questionId)).thenReturn(Optional.of(questionToUpdate));
8793
Mockito.when(questionRepository.save(questionCaptor.capture())).thenReturn(questionToUpdate);
8894

0 commit comments

Comments
 (0)