【问题标题】:spring boot: how to configure autowired WebTestClientspring boot:如何配置自动装配的 WebTestClient
【发布时间】:2019-10-21 16:09:18
【问题描述】:

Spring Boot 中是否有任何属性可用于配置 @Autowired WebTestClient?例如,如何在 WebTestClient 上设置 servlet 上下文路径(或者只是一些基本路径)?

这是我现在的网络测试配置方式:

@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
@ActiveProfiles("test")
public class MyTestClass{

  @Autowired
  private WebTestClient cl;

  //the rest of it
}

换句话说,什么是 Spring Boot 等价物

WebTestClient client = WebTestClient.bindToServer()
    .baseUrl("http://localhost:<random port>/myServletContext").build();

我没有在文档中找到任何有用的东西: https://docs.spring.io/spring-boot/docs/current/reference/html/common-application-properties.html

【问题讨论】:

    标签: spring spring-boot testing integration-testing


    【解决方案1】:

    使用当前应用程序上下文构建 webTestClient,无需硬编码 uri 和端口号

        @Autowired
        ApplicationContext context;
    
        @Autowired
        WebTestClient webTestClient;
    
        @Before
        public void setup() throws Exception {
    
            this.webTestClient = WebTestClient.bindToApplicationContext(this.context).build();
        }
    

    【讨论】:

      【解决方案2】:

      你可以使用server.servlet.context-path=/myServletContextPath之类的东西。

      【讨论】:

      • 不,它在服务器端设置上下文路径,但客户端假设它是/。这就是发布问题的全部意义所在。当然,我已经尝试过了。
      • 您是否碰巧查看了以下链接 - stackoverflow.com/questions/48226651/…
      • 是的,很久以前就评论过了。我不确定它与我的问题有什么关系。使用 @AutoConfigureWebTestClient 注释得到的结果与没有它时得到的结果相同。
      • 即使设置在服务端,客户端仍然可以通过声明来获取:@Value("${server.servlet.context-path:/defaultContext}") private String contextPath;
      猜你喜欢
      • 2019-05-03
      • 2018-06-21
      • 2019-06-14
      • 2017-09-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-23
      • 1970-01-01
      相关资源
      最近更新 更多