Mockito: Unterschied zwischen den Versionen

Aus Alexander's Wiki
Zeile 17: Zeile 17:
import static org.mockito.Mockito.when;
import static org.mockito.Mockito.when;


@SpringBootTest(classes = { CommentService.class })
class CommentServiceTest
{
    @Autowired
    protected CommentService                  commentService;
    @MockBean
    protected DocumentService                documentService;
   
         when(commentRepository.findByDocumentId(any())).thenReturn(List.of(
         when(commentRepository.findByDocumentId(any())).thenReturn(List.of(
                 Comment.builder().commentId(commentId1).build(),
                 Comment.builder().commentId(commentId1).build(),

Version vom 24. Januar 2023, 10:48 Uhr

Dependencies für Spring

<dependency>


</dependency>

Mocking

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.AdditionalAnswers.returnsFirstArg;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.when;

@SpringBootTest(classes = { CommentService.class })
class CommentServiceTest
{
    @Autowired
    protected CommentService                  commentService;
    @MockBean
    protected DocumentService                 documentService;

    
        when(commentRepository.findByDocumentId(any())).thenReturn(List.of(
                Comment.builder().commentId(commentId1).build(),
                Comment.builder().commentId(commentId2).build()
        ));
        
        when(replyPersistencePort.save(any())).thenAnswer(invocation ->
                invocation.getArgument(0)
        );
        
        when(commentPersistencePort.save(any())).then(returnsFirstArg());
        
        assertThat(status.get(0)).isEqualTo(ServiceState.OK);