Skip to content

Commit

Permalink
feat: add RestClient learning test (cho-log#18)
Browse files Browse the repository at this point in the history
* build: upgrade gradle version for 8.1.1

* feat: add RestClient learning test

* feat: add RestClient learning test with initial status
  • Loading branch information
byjo authored May 21, 2024
1 parent 35a7f73 commit 79b6948
Show file tree
Hide file tree
Showing 25 changed files with 478 additions and 14 deletions.
Binary file modified gradle/wrapper/gradle-wrapper.jar
Binary file not shown.
3 changes: 2 additions & 1 deletion gradle/wrapper/gradle-wrapper.properties
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-7.4-bin.zip
distributionUrl=https\://services.gradle.org/distributions/gradle-8.1.1-bin.zip
networkTimeout=10000
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
25 changes: 18 additions & 7 deletions gradlew
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@
# Darwin, MinGW, and NonStop.
#
# (3) This script is generated from the Groovy template
# https://github.com/gradle/gradle/blob/master/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
# https://github.com/gradle/gradle/blob/HEAD/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
# within the Gradle project.
#
# You can find Gradle at https://github.com/gradle/gradle/.
Expand All @@ -80,13 +80,10 @@ do
esac
done

APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit

APP_NAME="Gradle"
# This is normally unused
# shellcheck disable=SC2034
APP_BASE_NAME=${0##*/}

# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit

# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD=maximum
Expand Down Expand Up @@ -143,12 +140,16 @@ fi
if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
case $MAX_FD in #(
max*)
# In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC3045
MAX_FD=$( ulimit -H -n ) ||
warn "Could not query maximum file descriptor limit"
esac
case $MAX_FD in #(
'' | soft) :;; #(
*)
# In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC3045
ulimit -n "$MAX_FD" ||
warn "Could not set maximum file descriptor limit to $MAX_FD"
esac
Expand Down Expand Up @@ -193,6 +194,10 @@ if "$cygwin" || "$msys" ; then
done
fi


# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'

# Collect all arguments for the java command;
# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of
# shell script including quotes and variable substitutions, so put them in
Expand All @@ -205,6 +210,12 @@ set -- \
org.gradle.wrapper.GradleWrapperMain \
"$@"

# Stop when "xargs" is not available.
if ! command -v xargs >/dev/null 2>&1
then
die "xargs is not available"
fi

# Use "xargs" to parse quoted args.
#
# With -n1 it outputs one arg per line, with the quotes and backslashes removed.
Expand Down
15 changes: 9 additions & 6 deletions gradlew.bat
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
@rem limitations under the License.
@rem

@if "%DEBUG%" == "" @echo off
@if "%DEBUG%"=="" @echo off
@rem ##########################################################################
@rem
@rem Gradle startup script for Windows
Expand All @@ -25,7 +25,8 @@
if "%OS%"=="Windows_NT" setlocal

set DIRNAME=%~dp0
if "%DIRNAME%" == "" set DIRNAME=.
if "%DIRNAME%"=="" set DIRNAME=.
@rem This is normally unused
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%

Expand All @@ -40,7 +41,7 @@ if defined JAVA_HOME goto findJavaFromJavaHome

set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if "%ERRORLEVEL%" == "0" goto execute
if %ERRORLEVEL% equ 0 goto execute

echo.
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Expand Down Expand Up @@ -75,13 +76,15 @@ set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar

:end
@rem End local scope for the variables with windows NT shell
if "%ERRORLEVEL%"=="0" goto mainEnd
if %ERRORLEVEL% equ 0 goto mainEnd

:fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code!
if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
exit /b 1
set EXIT_CODE=%ERRORLEVEL%
if %EXIT_CODE% equ 0 set EXIT_CODE=1
if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE%
exit /b %EXIT_CODE%

:mainEnd
if "%OS%"=="Windows_NT" endlocal
Expand Down
2 changes: 2 additions & 0 deletions settings.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -20,3 +20,5 @@ include 'spring-data-jpa-2:initial'
include 'spring-data-jpa-2:complete'
include 'spring-auth-1:initial'
include 'spring-auth-1:complete'
include 'spring-http-client-1:initial'
include 'spring-http-client-1:complete'
75 changes: 75 additions & 0 deletions spring-http-client-1/complete/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
# 1. Spring의 HTTP 클라이언트

<br>

스프링 프레임워크는 다양한 HTTP 클라이언트를 제공하여 애플리케이션이 외부 API와 통신할 수 있도록 합니다.
스프링이 제공하는 HTTP 클라이언트에는 `RestClient`, `WebClient`, `RestTemplate` 이 있습니다.

이 문서에서는 스프링 6.1 버전에 추가된 `RestClient` 에 대해 다룹니다.

<br>

### 참조

- [Spring - REST Clients](https://docs.spring.io/spring-framework/reference/integration/rest-clients.html)
- [Spring blog - New in Spring 6.1: RestClient](https://spring.io/blog/2023/07/13/new-in-spring-6-1-restclient)

<br>

# 2. GET 요청 하기

<br>

`RestClient``get()` 메서드를 사용해 GET 요청을 할 수 있습니다.

<br>

### 학습 테스트
- 테스트 메서드: `cholog.RestClientTest.testGetTodos`
- 수행 방법
- `cholog.TodoRestClient.getTodos` 을 이용하여 학습 테스트를 성공시키세요.
- `TodoRestClient` 의 restClient 를 사용하여 Todo 목록을 조회합니다.
- Todo 목록 조회 url: http://jsonplaceholder.typicode.com/todos
- 외부 API의 host는 `RestClientConfig` 에 설정되어 있습니다.

<br>

# 3. GET 요청의 응답 변환하기

<br>

`RestClient``body()` 메서드를 사용해 응답을 원하는 POJO로 변환할 수 있습니다.

<br>

### 학습 테스트
- 테스트 메서드: `cholog.RestClientTest.testGetTodoWithId`
- 수행 방법
- `cholog.TodoRestClient.getTodoById` 을 이용하여 학습 테스트를 성공시키세요.
- `TodoRestClient` 의 restClient 를 사용하여 특정 id를 가진 Todo를 조회합니다.
- Todo 조회 url: http://jsonplaceholder.typicode.com/todos/1
- 응답 Body로 받은 `userId`, `id`, `title`, `completed` 값이 잘 매핑되도록 `Todo` 를 수정합니다.

<br>

# 4. 예외 처리

<br>

`RestClient``onStatus()` 메서드를 사용해 HTTP 응답 코드에 따라 예외처리를 할 수 있습니다.

<br>

### 학습 테스트
- 테스트 메서드: `cholog.RestClientTest.testGetTodoWithNonExistentId`
- 수행 방법
- `cholog.TodoRestClient.getTodoById` 을 이용하여 학습 테스트를 성공시키세요.
- 존재하지 않는 id에 대한 조회 요청을 했을 때, `TodoException.NotFound` 예외가 발생하도록 합니다.

<br>

# 5. 더 생각해보기

- 스프링이 제공하는 HTTP 클라이언트에는 각각 다른 성격과 사용 방법을 가지고 있습니다.
- `RestClient` 외의 다른 클라이언트에 대한 학습 테스트를 작성해 보며 차이점을 느껴봅니다.
- 각 클라이언트의 특징을 찾아보고 어떤 상황에 어떤 클라이언트를 택하는게 좋을지 생각해 봅니다.
22 changes: 22 additions & 0 deletions spring-http-client-1/complete/build.gradle
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
plugins {
id 'org.springframework.boot' version '3.2.5'
id 'io.spring.dependency-management' version '1.1.4'
id 'java'
}

group = 'cholog'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '17'

repositories {
mavenCentral()
}

dependencies {
implementation 'org.springframework.boot:spring-boot-starter-web'
testImplementation 'org.springframework.boot:spring-boot-starter-test'
}

test {
useJUnitPlatform()
}
1 change: 1 addition & 0 deletions spring-http-client-1/complete/settings.gradle
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
rootProject.name = 'spring-http-client-1'
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
package cholog;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestClient;

@Configuration
public class RestClientConfig {
@Bean
public TodoRestClient todoRestClient() {
return new TodoRestClient(
RestClient.builder().baseUrl("http://jsonplaceholder.typicode.com").build()
);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
package cholog;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class SpringClientApplication {

public static void main(String[] args) {
SpringApplication.run(SpringClientApplication.class, args);
}

}
24 changes: 24 additions & 0 deletions spring-http-client-1/complete/src/main/java/cholog/Todo.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
package cholog;

public class Todo {
private Long id;
private Long userId;
private String title;
private boolean completed;

public Long getId() {
return id;
}

public Long getUserId() {
return userId;
}

public String getTitle() {
return title;
}

public boolean isCompleted() {
return completed;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
package cholog;

public class TodoException extends RuntimeException {
public TodoException(String message) {
super(message);
}

public static class NotFound extends TodoException {
public NotFound(Long id) {
super("Todo not found with id: " + id);
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
package cholog;

import org.springframework.web.client.RestClient;

import java.util.Arrays;
import java.util.List;

public class TodoRestClient {
private final RestClient restClient;

public TodoRestClient(RestClient restClient) {
this.restClient = restClient;
}

public List<Todo> getTodos() {
Todo[] todoBody = restClient.get()
.uri("/todos")
.retrieve()
.body(Todo[].class);

return Arrays.asList(todoBody);
}

public Todo getTodoById(Long id) {
return restClient.get()
.uri("/todos/{id}", id)
.retrieve()
.onStatus(status -> status.value() == 404, (req, res) -> {
throw new TodoException.NotFound(id);
})
.body(Todo.class);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@

Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
package cholog;

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

import java.util.List;

import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;

@SpringBootTest
public class RestClientTest {

@Autowired
private TodoRestClient todoRestClient;

@Test
public void testGetTodos() {
List<Todo> todos = todoRestClient.getTodos();
assertThat(todos).isNotEmpty();
}

@Test
public void testGetTodoWithId() {
Todo todo = todoRestClient.getTodoById(1L);
assertThat(todo.getTitle()).isNotEmpty();
}

@Test
public void testGetTodoWithNonExistentId() {
Long nonExistentId = 9999L;

assertThatThrownBy(() -> todoRestClient.getTodoById(nonExistentId))
.isInstanceOf(TodoException.NotFound.class);
}
}
Loading

0 comments on commit 79b6948

Please sign in to comment.