Mockito

Aus Alexander's Wiki

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;
import static org.assertj.core.api.Assertions.assertThat;

@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);