【问题标题】:Using @WebFluxTest to test RouterFunction使用@WebFluxTest 测试RouterFunction
【发布时间】:2018-02-17 15:01:43
【问题描述】:

我有一个路由器功能,我想使用spock 进行测试。看起来是这样的

@Configuration
public class WebConfig {

    /**
     * Router function.
     * @return string
     */
    @Bean
    public RouterFunction<?> helloRoute() {
        return route(GET("/judge/router/hello"),
                request -> ServerResponse.ok().body(fromPublisher(Mono.just("Hello Router WebFlux"), String.class)));
    }

}

它的测试看起来像这样

@WebFluxTest
class JudgeRuleEngineMvcTestSpec extends Specification {

    @Autowired
    WebTestClient webClient;

    def "router function returns hello"() {
        expect:
            webClient.get().uri("/judge/router/hello")
                .exchange()
                .expectStatus().isOk()
                .expectBody(String.class)
                .isEqualTo("Hello WebFlux") // should fail
    }
}

但它失败了,因为它返回 404 而不是 200 状态。它似乎找不到REST 本身。

我还用GetMapping 对基本@9​​87654327@ 进行了测试,它工作正常。

@RestController
@RequestMapping("/judge/rest")
public class BasicController {
    private static final Logger LOGGER = LoggerFactory.getLogger(BasicController.class);

    @GetMapping("/hello")
    public Mono<String> handle() {
        LOGGER.debug("Invoking hello controller");
        return Mono.just("Hello WebFlux");
    }

}

def "mvc mono returns hello"() {
    expect:
        webClient.get().uri("/judge/rest/hello")
            .exchange()
            .expectStatus().isOk()
            .expectBody(String.class)
                .isEqualTo("Hello WebFlux")
}

为什么路由器功能会失败?

【问题讨论】:

    标签: spring spring-boot testing spock spring-webflux


    【解决方案1】:

    这是 @WebFluxTest 的已知限制 - 目前没有一致的方法来检测 RouterFunction bean,就像我们为 @Controller 类所做的那样。

    this Spring Boot issue for future reference

    【讨论】:

    • 所以没有办法测试它们?没有直接的方法调用或一些嵌入式服务器?
    • 目前没有 @WebFluxTest 等价物 - 所以是的,嵌入式服务器或直接测试它们是可行的方法。
    • 随着嵌入式数据库的兴起,是时候进行嵌入式服务器测试了lol
    【解决方案2】:

    要添加到Brian's answer,kizux 在他发布的 Github 问题链接中似乎提到了一种解决方法

    您可以通过bindToApplicationContext使用WebTestClient测试路由器功能

    引用

    @RunWith(SpringRunner.class)
    @ContextConfiguration(classes = {RouteConfiguration.class, UserHandler.class})
    @WebFluxTest
    public class UserHandlerTest
    {
        @Autowired
        private ApplicationContext context;
        @MockBean(name="userService")
        private UserService userService;
        private WebTestClient testClient;
    
        @Before
        public void setUp()
        {
            testClient = WebTestClient.bindToApplicationContext(context).build();
        }
    
        ...
    

    【讨论】:

      猜你喜欢
      • 2018-06-18
      • 2021-07-08
      • 2021-06-01
      • 1970-01-01
      • 1970-01-01
      • 2020-04-16
      • 2018-09-30
      • 2020-05-04
      • 2019-01-04
      相关资源
      最近更新 更多