# HG changeset patch # User Dirk Olmes # Date 1597327137 -7200 # Node ID 227f3105fedd6f4224afd473a062c8a88069ad83 # Parent 92d52e4ac567855f79404d410198552dd21d7542 Erster Unit Test, der das repository einfach nur mockt diff -r 92d52e4ac567 -r 227f3105fedd spring-boot-playground/pom.xml --- 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 @@ org.junit.vintage junit-vintage-engine + + junit + junit + - - - - - - + + org.junit.jupiter + junit-jupiter + 5.6.2 + test + org.hamcrest hamcrest diff -r 92d52e4ac567 -r 227f3105fedd spring-boot-playground/src/test/java/de/comline/spring/service/MovieServiceTest.java --- /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; + } + } +}