Mercurial > hg > SpringPlayground
changeset 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 | 92d52e4ac567 |
children | d57d0c6a841b |
files | spring-boot-playground/pom.xml spring-boot-playground/src/test/java/de/comline/spring/service/MovieServiceTest.java |
diffstat | 2 files changed, 58 insertions(+), 6 deletions(-) [+] |
line wrap: on
line diff
--- a/spring-boot-playground/pom.xml Thu Aug 13 15:31:38 2020 +0200 +++ b/spring-boot-playground/pom.xml Thu Aug 13 15:58:57 2020 +0200 @@ -60,14 +60,18 @@ <groupId>org.junit.vintage</groupId> <artifactId>junit-vintage-engine</artifactId> </exclusion> + <exclusion> + <groupId>junit</groupId> + <artifactId>junit</artifactId> + </exclusion> </exclusions> </dependency> -<!-- <dependency> --> -<!-- <groupId>org.junit.jupiter</groupId> --> -<!-- <artifactId>junit-jupiter</artifactId> --> -<!-- <version>5.6.2</version> --> -<!-- <scope>test</scope> --> -<!-- </dependency> --> + <dependency> + <groupId>org.junit.jupiter</groupId> + <artifactId>junit-jupiter</artifactId> + <version>5.6.2</version> + <scope>test</scope> + </dependency> <dependency> <groupId>org.hamcrest</groupId> <artifactId>hamcrest</artifactId>
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/spring-boot-playground/src/test/java/de/comline/spring/service/MovieServiceTest.java Thu Aug 13 15:58:57 2020 +0200 @@ -0,0 +1,48 @@ +package de.comline.spring.service; + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.is; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +import de.comline.spring.entity.Movie; +import de.comline.spring.repository.MovieRepository; +import de.comline.spring.service.MovieServiceTest.TestConfig; + +@SpringBootTest(classes = { + MovieService.class, + TestConfig.class +}) +public class MovieServiceTest { + @Autowired + private MovieService service; + + @Test + @DisplayName("Test with a mock movie repository") + void withMockRepository() { + String title = "the-movie-title"; + + Movie movie = service.createMovie(title); + assertThat(movie.getTitle(), is(title)); + } + + @Configuration + static class TestConfig { + @Bean + MovieRepository createMockRepository() { + MovieRepository mockRepository = mock(MovieRepository.class); + when(mockRepository.save(any())).thenAnswer(invocation -> { + return invocation.getArgument(0); + }); + return mockRepository; + } + } +}