# 46.3.11 자동 구성된 Spring WebFlux 테스트

[**Spring WebFlux**](https://docs.spring.io/spring/docs/5.1.8.RELEASE/spring-framework-reference//web-reactive.html) **컨트롤러가 예상대로 작동하는 지 테스트하려면 @WebFluxTest 어노테이션을 사용할 수 있습니다. `@WebFluxTest`는 Spring WebFlux 인프라를 자동으로 구성하고 스캔 빈을 `@Controller`, `@ControllerAdvice`, `@JsonComponent`, `Converter`, `GenericConverter`, 및`WebFluxConfigurer`로 제한합니다. `@WebFluxTest` 어노테이션을 사용하면 일반 `@Component` 빈은 검색되지 않습니다.**&#x20;

{% hint style="info" %}
스프링 웹플럭스

스프링5에서 새로 등장한, 웹 어플래케이션에서 리액티브 프로그래밍을 제공하는 프레임워크
{% endhint %}

| ![\[Tip\]](https://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/images/tip.png)                                                                        |
| ---------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `@WebFluxTest`가 사용할 수 있는 자동 구성 목록은 [found in the appendix](https://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#test-auto-configuration)에서 찾을 수 있습니다. |

| ![\[Tip\]](https://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/images/tip.png) |
| ----------------------------------------------------------------------------------------------- |
| Jackson `Module`과 같은 추가 구성 요소를 등록해야하는 경우 테스트에서 `@Import`를 사용하여 추가 구성 클래스를 가져올 수 있습니다.           |

**종종 `@WebFluxTest`는 단일 컨트롤러로 제한되며 `@MockBean` 어노테이션과 함께 사용하여 필요한 공동 작업자에게 모의 구현을 제공합니다.**&#x20;

{% hint style="info" %}
@MockBean :&#x20;

* spring-boot-test 패키지에서 제공 1.4\~ 가짜 객체를 만들어서 테스트할 수 있게 해준다. (@Autowired와 비슷하게 사용되고, 실제 객체가 아닌 가짜 객체가 주입된다)&#x20;
  * 기존에 사용되는 빈의 껍데기만 가져오고 내부의 구현 부분은 모두 사용자에게 위임한 형태

\[참고사이트] <https://jojoldu.tistory.com/226>
{% endhint %}

**`@WebFluxTest`는 또한 전체 HTTP 서버를 시작하지 않고도 WebFlux 컨트롤러를 신속하게 테스트 할 수 있는 강력한 방법을 제공하는** [**`WebTestClient`**](https://docs.spring.io/spring/docs/5.1.8.RELEASE/spring-framework-reference/testing.html#webtestclient)**를 자동 구성합니다.**&#x20;

{% hint style="info" %}
WebClient

* 스프링 5에 새롭게 추가된 기능으로, API에 대한 요청과 응답을 Non-blocking 방식으로 처리할 수 있다 (기존의 RestTemplate를 대체)&#x20;
  * RestTemplate의 경우 테스트를 위해 TestRestTemplate가 존재했음. 이와 같이 WebClient에도 테스트를 위한 WebTestClient를 제공한다.
    {% endhint %}

| ![\[Tip\]](https://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/images/tip.png)                                                                                       |
| ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `@AutoConfigureWebTestClient`로 어노테이션을 달아 non-`@WebFluxTest` (예 : `@SpringBootTest`)에서 `WebTestClient`를 자동 구성 할 수도 있습니다. 다음 예제에서는 `@WebFluxTest`와 `WebTestClient`를 모두 사용하는 클래스를 보여줍니다. |

```java
import org.junit.Test;
import org.junit.runner.RunWith;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.reactive.WebFluxTest;
import org.springframework.http.MediaType;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.reactive.server.WebTestClient;

@RunWith(SpringRunner.class)
@WebFluxTest(UserVehicleController.class)
public class MyControllerTests {

	@Autowired
	private WebTestClient webClient;

	@MockBean
	private UserVehicleService userVehicleService;

	@Test
	public void testExample() throws Exception {
		given(this.userVehicleService.getVehicleDetails("sboot"))
				.willReturn(new VehicleDetails("Honda", "Civic"));
		this.webClient.get().uri("/sboot/vehicle").accept(MediaType.TEXT_PLAIN)
				.exchange()
				.expectStatus().isOk()
				.expectBody(String.class).isEqualTo("Honda Civic");
	}

```

{% hint style="info" %}
`given`

* 해당 Mock Bean이 **어떤 행동을 취하면 어떤 결과를 반환한다**를 선언하는 부분입니다.
  {% endhint %}

| **이 설정은 모의 웹 응용 프로그램에서 `WebTestClient`를 사용하는 순간 WebFlux에서만 작동하므로 WebFlux 응용 프로그램에서만 지원됩니다.** |
| -------------------------------------------------------------------------------------------- |

| ![\[Note\]](https://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/images/note.png)                                                                           |
| --------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `@WebFluxTest`는 기능 웹 프레임 워크를 통해 등록된 경로를 감지 할 수 없습니다. 컨텍스트에서 `RouterFunction` Bean을 테스트하려면 `@Import`를 통해 자신의 `RouterFunction`을 가져 오거나 `@SpringBootTest`를 사용하여 가져 오는 것이 좋습니다. |

| ![\[Note\]](https://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/images/note.png)                                                                      |
| ---------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `@WebFluxTest`는 `SecurityWebFilterChain` 유형의 @Bean을 통해 등록 된 사용자 지정 보안 구성을 검색 할 수 없습니다. 이를 테스트에 포함 시키려면 `@Import`를 통해 Bean을 등록하는 구성을 가져 오거나 `@SpringBootTest`를 사용해야합니다. |

| ![\[Tip\]](https://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/images/tip.png)                                                                                                                                                                            |
| -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| 때떄로 Spring WebFlux 테스트를 작성하는 것만으로는 충분하지 않습니다. Spring Boot는 [full end-to-end tests with an actual server](https://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#boot-features-testing-spring-boot-applications-testing-with-running-server)를 수행하는 데 도움을줍니다. |


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://wannaqueen.gitbook.io/spring5/spring-boot/undefined-1/46.-testing/46.3-testing-spring-boot-applications/46.3.11-spring-webflux.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
