Mockito: Unterschied zwischen den Versionen
Aus Alexander's Wiki
Admin (Diskussion | Beiträge) (Die Seite wurde neu angelegt: „== Dependencies für Spring == <syntaxhighlight lang="xml"> <dependency> </dependency> </syntaxhighlight> == Mocking ==“) |
Admin (Diskussion | Beiträge) |
||
(2 dazwischenliegende Versionen desselben Benutzers werden nicht angezeigt) | |||
Zeile 8: | Zeile 8: | ||
== Mocking == | == Mocking == | ||
<syntaxhighlight lang="java"> | |||
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); | |||
</syntaxhighlight> |
Aktuelle Version vom 24. Januar 2023, 21:35 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;
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);