From e310fe84da7d5108415cfbd04d00131669ef77fd Mon Sep 17 00:00:00 2001 From: anuragkumawat Date: Thu, 30 Mar 2023 21:53:07 +0530 Subject: [PATCH] Move articles from spring-core-6 module to other spring-boot modules (#13722) * Move articles from spring-core-6 module to other spring-boot modules * JAVA-19559 Move articles from spring-core-6 module to other spring-boot-3 modules * JAVA-19559 Minor spacing change * JAVA-19559 Revert Minor spacing change --- spring-boot-modules/spring-boot-3/README.md | 1 + spring-boot-modules/spring-boot-3/pom.xml | 16 +- .../java/com/baeldung/httpinterface/Book.java | 0 .../baeldung/httpinterface/BooksClient.java | 0 .../baeldung/httpinterface/BooksService.java | 4 +- .../BooksServiceMockServerUnitTest.java | 0 .../BooksServiceMockitoUnitTest.java | 0 .../httpinterface/MyServiceException.java | 0 .../spring-boot-properties-3/README.md | 2 + .../envvariables/BaeldungProperties.java | 40 ++-- .../baeldung/envvariables/MyController.java | 120 +++++----- .../src/main/resources/application.properties | 7 +- .../MyControllerIntegrationTest.java | 72 +++--- spring-core-6/README.md | 3 +- spring-core-6/pom.xml | 15 -- .../src/main/resources/application.properties | 4 - .../BooksServiceMockServerTest.java | 217 ------------------ .../BooksServiceMockitoTest.java | 88 ------- 18 files changed, 143 insertions(+), 446 deletions(-) rename {spring-core-6 => spring-boot-modules/spring-boot-3}/src/main/java/com/baeldung/httpinterface/Book.java (100%) rename {spring-core-6 => spring-boot-modules/spring-boot-3}/src/main/java/com/baeldung/httpinterface/BooksClient.java (100%) rename {spring-core-6 => spring-boot-modules/spring-boot-3}/src/main/java/com/baeldung/httpinterface/BooksService.java (85%) create mode 100644 spring-boot-modules/spring-boot-3/src/test/java/com/baeldung/httpinterface/BooksServiceMockServerUnitTest.java create mode 100644 spring-boot-modules/spring-boot-3/src/test/java/com/baeldung/httpinterface/BooksServiceMockitoUnitTest.java rename {spring-core-6 => spring-boot-modules/spring-boot-3}/src/test/java/com/baeldung/httpinterface/MyServiceException.java (100%) rename {spring-core-6 => spring-boot-modules/spring-boot-properties-3}/src/main/java/com/baeldung/envvariables/BaeldungProperties.java (86%) rename {spring-core-6 => spring-boot-modules/spring-boot-properties-3}/src/main/java/com/baeldung/envvariables/MyController.java (94%) rename {spring-core-6 => spring-boot-modules/spring-boot-properties-3}/src/test/java/com/baeldung/envvariables/MyControllerIntegrationTest.java (95%) delete mode 100644 spring-core-6/src/test/java/com/baeldung/httpinterface/BooksServiceMockServerTest.java delete mode 100644 spring-core-6/src/test/java/com/baeldung/httpinterface/BooksServiceMockitoTest.java diff --git a/spring-boot-modules/spring-boot-3/README.md b/spring-boot-modules/spring-boot-3/README.md index 22a3311cfd..be95ce2830 100644 --- a/spring-boot-modules/spring-boot-3/README.md +++ b/spring-boot-modules/spring-boot-3/README.md @@ -5,3 +5,4 @@ - [Singleton Design Pattern vs Singleton Beans in Spring Boot](https://www.baeldung.com/spring-boot-singleton-vs-beans) - [Migrate Application From Spring Boot 2 to Spring Boot 3](https://www.baeldung.com/spring-boot-3-migration) - [Using Java Records with JPA](https://www.baeldung.com/spring-jpa-java-records) +- [HTTP Interface in Spring 6](https://www.baeldung.com/spring-6-http-interface) diff --git a/spring-boot-modules/spring-boot-3/pom.xml b/spring-boot-modules/spring-boot-3/pom.xml index 685df233ba..03740e805f 100644 --- a/spring-boot-modules/spring-boot-3/pom.xml +++ b/spring-boot-modules/spring-boot-3/pom.xml @@ -32,6 +32,20 @@ org.springframework.boot spring-boot-starter-data-jpa + + org.springframework.boot + spring-boot-starter-webflux + + + org.mock-server + mockserver-netty + ${mockserver.version} + + + org.mock-server + mockserver-client-java + ${mockserver.version} + com.h2database h2 @@ -125,7 +139,7 @@ 2.0.0 3.0.0-M7 com.baeldung.sample.TodoApplication - + 5.14.0 \ No newline at end of file diff --git a/spring-core-6/src/main/java/com/baeldung/httpinterface/Book.java b/spring-boot-modules/spring-boot-3/src/main/java/com/baeldung/httpinterface/Book.java similarity index 100% rename from spring-core-6/src/main/java/com/baeldung/httpinterface/Book.java rename to spring-boot-modules/spring-boot-3/src/main/java/com/baeldung/httpinterface/Book.java diff --git a/spring-core-6/src/main/java/com/baeldung/httpinterface/BooksClient.java b/spring-boot-modules/spring-boot-3/src/main/java/com/baeldung/httpinterface/BooksClient.java similarity index 100% rename from spring-core-6/src/main/java/com/baeldung/httpinterface/BooksClient.java rename to spring-boot-modules/spring-boot-3/src/main/java/com/baeldung/httpinterface/BooksClient.java diff --git a/spring-core-6/src/main/java/com/baeldung/httpinterface/BooksService.java b/spring-boot-modules/spring-boot-3/src/main/java/com/baeldung/httpinterface/BooksService.java similarity index 85% rename from spring-core-6/src/main/java/com/baeldung/httpinterface/BooksService.java rename to spring-boot-modules/spring-boot-3/src/main/java/com/baeldung/httpinterface/BooksService.java index a9cf6ec58a..a70d412dd2 100644 --- a/spring-core-6/src/main/java/com/baeldung/httpinterface/BooksService.java +++ b/spring-boot-modules/spring-boot-3/src/main/java/com/baeldung/httpinterface/BooksService.java @@ -15,12 +15,12 @@ interface BooksService { List getBooks(); @GetExchange("/books/{id}") - Book getBook(@PathVariable long id); + Book getBook(@PathVariable("id") long id); @PostExchange("/books") Book saveBook(@RequestBody Book book); @DeleteExchange("/books/{id}") - ResponseEntity deleteBook(@PathVariable long id); + ResponseEntity deleteBook(@PathVariable("id") long id); } diff --git a/spring-boot-modules/spring-boot-3/src/test/java/com/baeldung/httpinterface/BooksServiceMockServerUnitTest.java b/spring-boot-modules/spring-boot-3/src/test/java/com/baeldung/httpinterface/BooksServiceMockServerUnitTest.java new file mode 100644 index 0000000000..e69de29bb2 diff --git a/spring-boot-modules/spring-boot-3/src/test/java/com/baeldung/httpinterface/BooksServiceMockitoUnitTest.java b/spring-boot-modules/spring-boot-3/src/test/java/com/baeldung/httpinterface/BooksServiceMockitoUnitTest.java new file mode 100644 index 0000000000..e69de29bb2 diff --git a/spring-core-6/src/test/java/com/baeldung/httpinterface/MyServiceException.java b/spring-boot-modules/spring-boot-3/src/test/java/com/baeldung/httpinterface/MyServiceException.java similarity index 100% rename from spring-core-6/src/test/java/com/baeldung/httpinterface/MyServiceException.java rename to spring-boot-modules/spring-boot-3/src/test/java/com/baeldung/httpinterface/MyServiceException.java diff --git a/spring-boot-modules/spring-boot-properties-3/README.md b/spring-boot-modules/spring-boot-properties-3/README.md index 77c6815649..37b63abb84 100644 --- a/spring-boot-modules/spring-boot-properties-3/README.md +++ b/spring-boot-modules/spring-boot-properties-3/README.md @@ -10,3 +10,5 @@ - [Load Spring Boot Properties From a JSON File](https://www.baeldung.com/spring-boot-json-properties) - [IntelliJ – Cannot Resolve Spring Boot Configuration Properties Error](https://www.baeldung.com/intellij-resolve-spring-boot-configuration-properties) - [Log Properties in a Spring Boot Application](https://www.baeldung.com/spring-boot-log-properties) +- [Using Environment Variables in Spring Boot’s application.properties](https://www.baeldung.com/spring-boot-properties-env-variables) +- More articles: [[<-- prev]](../spring-boot-properties-2) diff --git a/spring-core-6/src/main/java/com/baeldung/envvariables/BaeldungProperties.java b/spring-boot-modules/spring-boot-properties-3/src/main/java/com/baeldung/envvariables/BaeldungProperties.java similarity index 86% rename from spring-core-6/src/main/java/com/baeldung/envvariables/BaeldungProperties.java rename to spring-boot-modules/spring-boot-properties-3/src/main/java/com/baeldung/envvariables/BaeldungProperties.java index a41ac7a509..0e6e05a3c2 100644 --- a/spring-core-6/src/main/java/com/baeldung/envvariables/BaeldungProperties.java +++ b/spring-boot-modules/spring-boot-properties-3/src/main/java/com/baeldung/envvariables/BaeldungProperties.java @@ -1,20 +1,20 @@ -package com.baeldung.envvariables.valueinjection; - -import org.springframework.boot.context.properties.ConfigurationProperties; -import org.springframework.stereotype.Component; - -@Component -@ConfigurationProperties(prefix = "baeldung") -public class BaeldungProperties { - - private String presentation; - - public String getPresentation() { - return presentation; - } - - public void setPresentation(String presentation) { - this.presentation = presentation; - } - -} +package com.baeldung.envvariables; + +import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.stereotype.Component; + +@Component +@ConfigurationProperties(prefix = "baeldung") +public class BaeldungProperties { + + private String presentation; + + public String getPresentation() { + return presentation; + } + + public void setPresentation(String presentation) { + this.presentation = presentation; + } + +} diff --git a/spring-core-6/src/main/java/com/baeldung/envvariables/MyController.java b/spring-boot-modules/spring-boot-properties-3/src/main/java/com/baeldung/envvariables/MyController.java similarity index 94% rename from spring-core-6/src/main/java/com/baeldung/envvariables/MyController.java rename to spring-boot-modules/spring-boot-properties-3/src/main/java/com/baeldung/envvariables/MyController.java index 503ee47157..6afe9f2de1 100644 --- a/spring-core-6/src/main/java/com/baeldung/envvariables/MyController.java +++ b/spring-boot-modules/spring-boot-properties-3/src/main/java/com/baeldung/envvariables/MyController.java @@ -1,60 +1,60 @@ -package com.baeldung.envvariables.valueinjection; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.core.env.Environment; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.RestController; - -@RestController -public class MyController { - - @Value("${environment.name}") - private String environmentName; - - @Value("${java.home.and.environment}") - private String javaHomeAndEnvironmentName; - - @Value("${thispropertydoesnotexist}") - private String nonExistentProperty; - - @Value("${baeldung.presentation}") - private String baeldungPresentation; - - @Autowired - private Environment environment; - - @Autowired - private BaeldungProperties baeldungProperties; - - @GetMapping("/environment_name") - String getEnvironmentName_FromEnvironmentVariables() { - return environmentName; - } - - @GetMapping("/java_home_and_environment") - String getJavaHomeAndEnvironmentName_FromEnvironmentVariables() { - return javaHomeAndEnvironmentName; - } - - @GetMapping("non_existent_property") - String getNonexistentProperty_FromEnvironmentVariables() { - return nonExistentProperty; - } - - @GetMapping("baeldung_presentation_from_value") - String getBaeldungPresentation_FromValue() { - return baeldungPresentation; - } - - @GetMapping("baeldung_presentation_from_environment") - String getBaeldungPresentation_FromEnvironment() { - return environment.getProperty("baeldung.presentation"); - } - - @GetMapping("baeldung_configuration_properties") - String getBaeldungPresentation_FromConfigurationProperties() { - return baeldungProperties.getPresentation(); - } - -} +package com.baeldung.envvariables; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.core.env.Environment; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RestController; + +@RestController +public class MyController { + + @Value("${environment.name}") + private String environmentName; + + @Value("${java.home.and.environment}") + private String javaHomeAndEnvironmentName; + + @Value("${thispropertydoesnotexist}") + private String nonExistentProperty; + + @Value("${baeldung.presentation}") + private String baeldungPresentation; + + @Autowired + private Environment environment; + + @Autowired + private BaeldungProperties baeldungProperties; + + @GetMapping("/environment_name") + String getEnvironmentName_FromEnvironmentVariables() { + return environmentName; + } + + @GetMapping("/java_home_and_environment") + String getJavaHomeAndEnvironmentName_FromEnvironmentVariables() { + return javaHomeAndEnvironmentName; + } + + @GetMapping("non_existent_property") + String getNonexistentProperty_FromEnvironmentVariables() { + return nonExistentProperty; + } + + @GetMapping("baeldung_presentation_from_value") + String getBaeldungPresentation_FromValue() { + return baeldungPresentation; + } + + @GetMapping("baeldung_presentation_from_environment") + String getBaeldungPresentation_FromEnvironment() { + return environment.getProperty("baeldung.presentation"); + } + + @GetMapping("baeldung_configuration_properties") + String getBaeldungPresentation_FromConfigurationProperties() { + return baeldungProperties.getPresentation(); + } + +} diff --git a/spring-boot-modules/spring-boot-properties-3/src/main/resources/application.properties b/spring-boot-modules/spring-boot-properties-3/src/main/resources/application.properties index a079837942..541183a186 100644 --- a/spring-boot-modules/spring-boot-properties-3/src/main/resources/application.properties +++ b/spring-boot-modules/spring-boot-properties-3/src/main/resources/application.properties @@ -26,4 +26,9 @@ spring.config.activate.on-profile=multidocument-prod spring.datasource.password=password spring.datasource.url=jdbc:h2:prod spring.datasource.username=prodUser -bael.property=prodValue \ No newline at end of file +bael.property=prodValue +#--- +environment.name=${OS} +java.home.and.environment=${JAVA_HOME}+${OS} +not.existing.system.property=${thispropertydoesnotexist} +baeldung.presentation=${HELLO_BAELDUNG}. Java is installed in the folder: ${JAVA_HOME} \ No newline at end of file diff --git a/spring-core-6/src/test/java/com/baeldung/envvariables/MyControllerIntegrationTest.java b/spring-boot-modules/spring-boot-properties-3/src/test/java/com/baeldung/envvariables/MyControllerIntegrationTest.java similarity index 95% rename from spring-core-6/src/test/java/com/baeldung/envvariables/MyControllerIntegrationTest.java rename to spring-boot-modules/spring-boot-properties-3/src/test/java/com/baeldung/envvariables/MyControllerIntegrationTest.java index b3ee2c7c46..527acd5dfc 100644 --- a/spring-core-6/src/test/java/com/baeldung/envvariables/MyControllerIntegrationTest.java +++ b/spring-boot-modules/spring-boot-properties-3/src/test/java/com/baeldung/envvariables/MyControllerIntegrationTest.java @@ -1,36 +1,36 @@ -package com.baeldung.envvariables.valueinjection; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.test.web.servlet.MockMvc; - -@SpringBootTest(classes = MyController.class) -@AutoConfigureMockMvc -public class MyControllerIntegrationTest { - - @Autowired - private MockMvc mockMvc; - - /** NB : these tests are commented out because they are environment dependent - * If you want to run one of them on your machine, follow the instruction above it - * - * expects the value of your system environment property 'OS' (it is already defined at least in Windows_NT) - @Test void givenExistingSystemProperty_whenInjected_thenHasSystemPropertyValue() throws Exception { - mockMvc.perform(get("/environment_name")) - .andExpect(content().string(equalTo("Windows_NT"))); - } - - * expects the value of the JAVA_HOME environment variable (you need to define it if you haven't yet), with a + and the 'OS' environment property in the end - @Test void givenCombinationOfSystemPropertyAndEnvironmentVariable_whenInjected_thenHasExpectedValue() throws Exception { - mockMvc.perform(get("/java_home_and_environment")) - .andExpect(content().string(equalTo("C:\\Program Files\\Java\\jdk-11.0.14+Windows_NT"))); - } - - * expects the content to be ${thispropertydoesnotexist} ; if you have defined an environment property called thispropertydoesnotexist, it would fail - @Test void givenNonExistentProperty_whenInjected_thenKeepsTheStringValue() throws Exception { - mockMvc.perform(get("/non_existent_property")) - .andExpect(content().string(equalTo("${thispropertydoesnotexist}"))); - } - */ -} +package com.baeldung.envvariables; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.web.servlet.MockMvc; + +@SpringBootTest(classes = MyController.class) +@AutoConfigureMockMvc +public class MyControllerIntegrationTest { + + @Autowired + private MockMvc mockMvc; + + /** NB : these tests are commented out because they are environment dependent + * If you want to run one of them on your machine, follow the instruction above it + * + * expects the value of your system environment property 'OS' (it is already defined at least in Windows_NT) + @Test void givenExistingSystemProperty_whenInjected_thenHasSystemPropertyValue() throws Exception { + mockMvc.perform(get("/environment_name")) + .andExpect(content().string(equalTo("Windows_NT"))); + } + + * expects the value of the JAVA_HOME environment variable (you need to define it if you haven't yet), with a + and the 'OS' environment property in the end + @Test void givenCombinationOfSystemPropertyAndEnvironmentVariable_whenInjected_thenHasExpectedValue() throws Exception { + mockMvc.perform(get("/java_home_and_environment")) + .andExpect(content().string(equalTo("C:\\Program Files\\Java\\jdk-11.0.14+Windows_NT"))); + } + + * expects the content to be ${thispropertydoesnotexist} ; if you have defined an environment property called thispropertydoesnotexist, it would fail + @Test void givenNonExistentProperty_whenInjected_thenKeepsTheStringValue() throws Exception { + mockMvc.perform(get("/non_existent_property")) + .andExpect(content().string(equalTo("${thispropertydoesnotexist}"))); + } + */ +} diff --git a/spring-core-6/README.md b/spring-core-6/README.md index af9fd7e32c..1879ff9a68 100644 --- a/spring-core-6/README.md +++ b/spring-core-6/README.md @@ -1,6 +1,5 @@ ### Relevant Articles: -- [Using Environment Variables in Spring Boot’s application.properties](https://www.baeldung.com/spring-boot-properties-env-variables) - [Reinitialize Singleton Bean in Spring Context](https://www.baeldung.com/spring-reinitialize-singleton-bean) -- [HTTP Interface in Spring 6](https://www.baeldung.com/spring-6-http-interface) - [Getting the Current ApplicationContext in Spring](https://www.baeldung.com/spring-get-current-applicationcontext) +- More articles: [[<-- prev]](../spring-core-5) \ No newline at end of file diff --git a/spring-core-6/pom.xml b/spring-core-6/pom.xml index a3dda0374f..cc494b3a57 100644 --- a/spring-core-6/pom.xml +++ b/spring-core-6/pom.xml @@ -21,20 +21,6 @@ org.springframework.boot spring-boot-starter-web - - org.springframework.boot - spring-boot-starter-webflux - - - org.mock-server - mockserver-netty - ${mockserver.version} - - - org.mock-server - mockserver-client-java - ${mockserver.version} - org.springframework.boot spring-boot-starter-test @@ -104,7 +90,6 @@ UTF-8 17 17 - 5.14.0 \ No newline at end of file diff --git a/spring-core-6/src/main/resources/application.properties b/spring-core-6/src/main/resources/application.properties index 28a65dce32..6545cd1097 100644 --- a/spring-core-6/src/main/resources/application.properties +++ b/spring-core-6/src/main/resources/application.properties @@ -1,5 +1 @@ -environment.name=${OS} -java.home.and.environment=${JAVA_HOME}+${OS} -not.existing.system.property=${thispropertydoesnotexist} -baeldung.presentation=${HELLO_BAELDUNG}. Java is installed in the folder: ${JAVA_HOME} config.file.path=./spring-core-6/src/main/resources/config.properties \ No newline at end of file diff --git a/spring-core-6/src/test/java/com/baeldung/httpinterface/BooksServiceMockServerTest.java b/spring-core-6/src/test/java/com/baeldung/httpinterface/BooksServiceMockServerTest.java deleted file mode 100644 index 22e00c16ae..0000000000 --- a/spring-core-6/src/test/java/com/baeldung/httpinterface/BooksServiceMockServerTest.java +++ /dev/null @@ -1,217 +0,0 @@ -package com.baeldung.httpinterface; - -import org.apache.http.HttpException; -import org.apache.http.HttpStatus; -import org.junit.jupiter.api.AfterAll; -import org.junit.jupiter.api.BeforeAll; -import org.junit.jupiter.api.Test; -import org.mockserver.client.MockServerClient; -import org.mockserver.integration.ClientAndServer; -import org.mockserver.configuration.Configuration; - -import java.io.IOException; -import java.net.ServerSocket; -import java.util.List; - -import org.mockserver.model.HttpRequest; -import org.mockserver.model.MediaType; -import org.mockserver.verify.VerificationTimes; -import org.slf4j.event.Level; -import org.springframework.http.HttpMethod; -import org.springframework.http.HttpStatusCode; -import org.springframework.http.ResponseEntity; -import org.springframework.web.reactive.function.client.WebClient; -import org.springframework.web.reactive.function.client.WebClientResponseException; -import reactor.core.publisher.Mono; - -import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.junit.jupiter.api.Assertions.assertTrue; -import static org.mockserver.integration.ClientAndServer.startClientAndServer; -import static org.mockserver.matchers.Times.exactly; -import static org.mockserver.model.HttpRequest.request; -import static org.mockserver.model.HttpResponse.response; -import static org.junit.jupiter.api.Assertions.assertEquals; - -class BooksServiceMockServerTest { - - private static final String SERVER_ADDRESS = "localhost"; - private static final String PATH = "/books"; - - private static int serverPort; - private static ClientAndServer mockServer; - private static String serviceUrl; - - @BeforeAll - static void startServer() throws IOException { - serverPort = getFreePort(); - serviceUrl = "http://" + SERVER_ADDRESS + ":" + serverPort; - - Configuration config = Configuration.configuration().logLevel(Level.WARN); - mockServer = startClientAndServer(config, serverPort); - - mockAllBooksRequest(); - mockBookByIdRequest(); - mockSaveBookRequest(); - mockDeleteBookRequest(); - } - - @AfterAll - static void stopServer() { - mockServer.stop(); - } - - @Test - void givenMockedGetResponse_whenGetBooksServiceMethodIsCalled_thenTwoBooksAreReturned() { - BooksClient booksClient = new BooksClient(WebClient.builder().baseUrl(serviceUrl).build()); - BooksService booksService = booksClient.getBooksService(); - - List books = booksService.getBooks(); - assertEquals(2, books.size()); - - mockServer.verify( - HttpRequest.request() - .withMethod(HttpMethod.GET.name()) - .withPath(PATH), - VerificationTimes.exactly(1) - ); - } - - @Test - void givenMockedGetResponse_whenGetExistingBookServiceMethodIsCalled_thenCorrectBookIsReturned() { - BooksClient booksClient = new BooksClient(WebClient.builder().baseUrl(serviceUrl).build()); - BooksService booksService = booksClient.getBooksService(); - - Book book = booksService.getBook(1); - assertEquals("Book_1", book.title()); - - mockServer.verify( - HttpRequest.request() - .withMethod(HttpMethod.GET.name()) - .withPath(PATH + "/1"), - VerificationTimes.exactly(1) - ); - } - - @Test - void givenMockedGetResponse_whenGetNonExistingBookServiceMethodIsCalled_thenCorrectBookIsReturned() { - BooksClient booksClient = new BooksClient(WebClient.builder().baseUrl(serviceUrl).build()); - BooksService booksService = booksClient.getBooksService(); - - assertThrows(WebClientResponseException.class, () -> booksService.getBook(9)); - } - - @Test - void givenCustomErrorHandlerIsSet_whenGetNonExistingBookServiceMethodIsCalled_thenCustomExceptionIsThrown() { - BooksClient booksClient = new BooksClient(WebClient.builder() - .defaultStatusHandler(HttpStatusCode::isError, resp -> - Mono.just(new MyServiceException("Custom exception"))) - .baseUrl(serviceUrl) - .build()); - - BooksService booksService = booksClient.getBooksService(); - assertThrows(MyServiceException.class, () -> booksService.getBook(9)); - } - - @Test - void givenMockedPostResponse_whenSaveBookServiceMethodIsCalled_thenCorrectBookIsReturned() { - BooksClient booksClient = new BooksClient(WebClient.builder().baseUrl(serviceUrl).build()); - BooksService booksService = booksClient.getBooksService(); - - Book book = booksService.saveBook(new Book(3, "Book_3", "Author_3", 2000)); - assertEquals("Book_3", book.title()); - - mockServer.verify( - HttpRequest.request() - .withMethod(HttpMethod.POST.name()) - .withPath(PATH), - VerificationTimes.exactly(1) - ); - } - - @Test - void givenMockedDeleteResponse_whenDeleteBookServiceMethodIsCalled_thenCorrectCodeIsReturned() { - BooksClient booksClient = new BooksClient(WebClient.builder().baseUrl(serviceUrl).build()); - BooksService booksService = booksClient.getBooksService(); - - ResponseEntity response = booksService.deleteBook(3); - assertEquals(HttpStatusCode.valueOf(200), response.getStatusCode()); - - mockServer.verify( - HttpRequest.request() - .withMethod(HttpMethod.DELETE.name()) - .withPath(PATH + "/3"), - VerificationTimes.exactly(1) - ); - } - - private static int getFreePort () throws IOException { - try (ServerSocket serverSocket = new ServerSocket(0)) { - return serverSocket.getLocalPort(); - } - } - - private static void mockAllBooksRequest() { - new MockServerClient(SERVER_ADDRESS, serverPort) - .when( - request() - .withPath(PATH) - .withMethod(HttpMethod.GET.name()), - exactly(1) - ) - .respond( - response() - .withStatusCode(HttpStatus.SC_OK) - .withContentType(MediaType.APPLICATION_JSON) - .withBody("[{\"id\":1,\"title\":\"Book_1\",\"author\":\"Author_1\",\"year\":1998},{\"id\":2,\"title\":\"Book_2\",\"author\":\"Author_2\",\"year\":1999}]") - ); - } - - private static void mockBookByIdRequest() { - new MockServerClient(SERVER_ADDRESS, serverPort) - .when( - request() - .withPath(PATH + "/1") - .withMethod(HttpMethod.GET.name()), - exactly(1) - ) - .respond( - response() - .withStatusCode(HttpStatus.SC_OK) - .withContentType(MediaType.APPLICATION_JSON) - .withBody("{\"id\":1,\"title\":\"Book_1\",\"author\":\"Author_1\",\"year\":1998}") - ); - } - - private static void mockSaveBookRequest() { - new MockServerClient(SERVER_ADDRESS, serverPort) - .when( - request() - .withPath(PATH) - .withMethod(HttpMethod.POST.name()) - .withContentType(MediaType.APPLICATION_JSON) - .withBody("{\"id\":3,\"title\":\"Book_3\",\"author\":\"Author_3\",\"year\":2000}"), - exactly(1) - ) - .respond( - response() - .withStatusCode(HttpStatus.SC_OK) - .withContentType(MediaType.APPLICATION_JSON) - .withBody("{\"id\":3,\"title\":\"Book_3\",\"author\":\"Author_3\",\"year\":2000}") - ); - } - - private static void mockDeleteBookRequest() { - new MockServerClient(SERVER_ADDRESS, serverPort) - .when( - request() - .withPath(PATH + "/3") - .withMethod(HttpMethod.DELETE.name()), - exactly(1) - ) - .respond( - response() - .withStatusCode(HttpStatus.SC_OK) - ); - } - -} diff --git a/spring-core-6/src/test/java/com/baeldung/httpinterface/BooksServiceMockitoTest.java b/spring-core-6/src/test/java/com/baeldung/httpinterface/BooksServiceMockitoTest.java deleted file mode 100644 index 7a82835ef3..0000000000 --- a/spring-core-6/src/test/java/com/baeldung/httpinterface/BooksServiceMockitoTest.java +++ /dev/null @@ -1,88 +0,0 @@ -package com.baeldung.httpinterface; - -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.extension.ExtendWith; -import org.mockito.Answers; -import org.mockito.InjectMocks; -import org.mockito.Mock; -import org.mockito.junit.jupiter.MockitoExtension; -import org.springframework.core.ParameterizedTypeReference; -import org.springframework.http.HttpMethod; -import org.springframework.http.HttpStatusCode; -import org.springframework.http.ResponseEntity; -import org.springframework.web.reactive.function.client.WebClient; -import reactor.core.publisher.Mono; - -import static org.mockito.BDDMockito.*; - -import java.util.List; - -import static org.junit.jupiter.api.Assertions.assertEquals; - -@ExtendWith(MockitoExtension.class) -class BooksServiceMockitoTest { - - @Mock(answer = Answers.RETURNS_DEEP_STUBS) - private WebClient webClient; - - @InjectMocks - private BooksClient booksClient; - - @Test - void givenMockedWebClientReturnsTwoBooks_whenGetBooksServiceMethodIsCalled_thenListOfTwoBooksIsReturned() { - given(webClient.method(HttpMethod.GET) - .uri(anyString(), anyMap()) - .retrieve() - .bodyToMono(new ParameterizedTypeReference>(){})) - .willReturn(Mono.just(List.of( - new Book(1,"Book_1", "Author_1", 1998), - new Book(2, "Book_2", "Author_2", 1999) - ))); - - BooksService booksService = booksClient.getBooksService(); - List books = booksService.getBooks(); - assertEquals(2, books.size()); - } - - @Test - void givenMockedWebClientReturnsBook_whenGetBookServiceMethodIsCalled_thenBookIsReturned() { - given(webClient.method(HttpMethod.GET) - .uri(anyString(), anyMap()) - .retrieve() - .bodyToMono(new ParameterizedTypeReference(){})) - .willReturn(Mono.just(new Book(1,"Book_1", "Author_1", 1998))); - - BooksService booksService = booksClient.getBooksService(); - Book book = booksService.getBook(1); - assertEquals("Book_1", book.title()); - } - - @Test - void givenMockedWebClientReturnsBook_whenSaveBookServiceMethodIsCalled_thenBookIsReturned() { - given(webClient.method(HttpMethod.POST) - .uri(anyString(), anyMap()) - .retrieve() - .bodyToMono(new ParameterizedTypeReference(){})) - .willReturn(Mono.just(new Book(3, "Book_3", "Author_3", 2000))); - - BooksService booksService = booksClient.getBooksService(); - Book book = booksService.saveBook(new Book(3, "Book_3", "Author_3", 2000)); - assertEquals("Book_3", book.title()); - } - - @Test - void givenMockedWebClientReturnsOk_whenDeleteBookServiceMethodIsCalled_thenOkCodeIsReturned() { - given(webClient.method(HttpMethod.DELETE) - .uri(anyString(), anyMap()) - .retrieve() - .toBodilessEntity() - .block(any()) - .getStatusCode()) - .willReturn(HttpStatusCode.valueOf(200)); - - BooksService booksService = booksClient.getBooksService(); - ResponseEntity response = booksService.deleteBook(3); - assertEquals(HttpStatusCode.valueOf(200), response.getStatusCode()); - } - -}