comparison spring-boot-playground/src/test/java/de/comline/spring/service/MovieServiceTest.java @ 5:227f3105fedd

Erster Unit Test, der das repository einfach nur mockt
author Dirk Olmes <dirk.olmes@codedo.de>
date Thu, 13 Aug 2020 15:58:57 +0200
parents
children
comparison
equal deleted inserted replaced
4:92d52e4ac567 5:227f3105fedd
1 package de.comline.spring.service;
2
3 import static org.hamcrest.MatcherAssert.assertThat;
4 import static org.hamcrest.Matchers.is;
5 import static org.mockito.ArgumentMatchers.any;
6 import static org.mockito.Mockito.mock;
7 import static org.mockito.Mockito.when;
8
9 import org.junit.jupiter.api.DisplayName;
10 import org.junit.jupiter.api.Test;
11 import org.springframework.beans.factory.annotation.Autowired;
12 import org.springframework.boot.test.context.SpringBootTest;
13 import org.springframework.context.annotation.Bean;
14 import org.springframework.context.annotation.Configuration;
15
16 import de.comline.spring.entity.Movie;
17 import de.comline.spring.repository.MovieRepository;
18 import de.comline.spring.service.MovieServiceTest.TestConfig;
19
20 @SpringBootTest(classes = {
21 MovieService.class,
22 TestConfig.class
23 })
24 public class MovieServiceTest {
25 @Autowired
26 private MovieService service;
27
28 @Test
29 @DisplayName("Test with a mock movie repository")
30 void withMockRepository() {
31 String title = "the-movie-title";
32
33 Movie movie = service.createMovie(title);
34 assertThat(movie.getTitle(), is(title));
35 }
36
37 @Configuration
38 static class TestConfig {
39 @Bean
40 MovieRepository createMockRepository() {
41 MovieRepository mockRepository = mock(MovieRepository.class);
42 when(mockRepository.save(any())).thenAnswer(invocation -> {
43 return invocation.getArgument(0);
44 });
45 return mockRepository;
46 }
47 }
48 }