首页 > 解决方案 > 使用 Spring WebFlux 和 Controller 测试失败

问题描述

我正在尝试使用 Spring Webflux 为 Spring Controller 编写单元测试。以下是控制器:

@Controller
public class MyController {

    private Service service;

    public MyController (Service service) {
        this.service=service;
    }

    @GetMapping({"", "/", "/index"})
    public String createChain(Model model) {
        model.addAttribute("blockchain", service.getString());

        return "index";
    }

}

这是底层服务接口:

public interface Service{

    Mono<String> getString();

}

这是测试类:

@RunWith(SpringRunner.class)
@WebFluxTest(MyController.class)
public class MyControllerTest {

    @Autowired
    private WebTestClient webTestClient;

    @MockBean
    private Service service;

    @Test
    public void getAString() {

        BDDMockito.given(service.getString()).willReturn(Mono.just("A string."));

        this.webTestClient.get().uri("/").exchange()
                .expectStatus().isOk();

    }
}

如您所见,我只是试图从反应式服务中检索字符串,并将该字符串放入 html 模板中(我使用 Thymeleaf 作为模板引擎)。但是,我不断收到以下异常:

java.lang.IllegalStateException:无法解析名称为“索引”的视图。在 org.springframework.web.reactive.result.view.ViewResolutionResultHandler.lambda$resolveViews$3(ViewResolutionResultHandler.java:276) ~[spring-webflux-5.1.4.RELEASE.jar:5.1.4.RELEASE] 在 reactor.core .publisher.FluxMapFuseable$MapFuseableSubscriber.onNext(FluxMapFuseable.java:107) [reactor-core-3.2.5.RELEASE.jar:3.2.5.RELEASE] 在 reactor.core.publisher.Operators$MonoSubscriber.complete(Operators.java :1505) ~[reactor-core-3.2.5.RELEASE.jar:3.2.5.RELEASE] 在 reactor.core.publisher.MonoCollectList$MonoBufferAllSubscriber.onComplete(MonoCollectList.java:118) ~[reactor-core-3.2. 5.RELEASE.jar:3.2.5.RELEASE] 在 reactor.core.publisher.FluxConcatMap$ConcatMapImmediate.drain(FluxConcatMap.java:360) ~[reactor-core-3.2.5.RELEASE.jar:3.2.5。

我不明白出了什么问题。命名的模板index.html位于src/main/resources/templates/index.html.

谢谢您的支持!

标签: javaspringunit-testingspring-webflux

解决方案


WebFluxTest:使用此注解将禁用完全自动配置,而是仅应用与 WebFlux 测试相关的配置(即 @Controller、@ControllerAdvice、@JsonComponent、Converter/GenericConverter 和 WebFluxConfigurer bean,但不是 @Component、@Service 或 @Repository bean) .

如果您希望加载完整的应用程序配置并使用 WebTestClient,则应考虑将 @SpringBootTest 与 @AutoConfigureWebTestClient 结合使用,而不是使用此注解。

WebFluxTest 文档


@RunWith(SpringRunner.class)
@SpringBootTest
@AutoConfigureWebTestClient
public class MyControllerTest {

    @Autowired
    private WebTestClient webTestClient;

    @MockBean
    private Service service;

    @Test
    public void getAString() {

        BDDMockito.given(service.getString()).willReturn(Mono.just("A string."));

        this.webTestClient.get().uri("/").exchange()
                .expectStatus().isOk();

    }
}

推荐阅读