6

Are there any properties available in Spring Boot to configure the @Autowired WebTestClient? For instance, how to set the servlet context path (or just some base path for that matter) on WebTestClient?

Here's how my web tests are configured now:

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

  @Autowired
  private WebTestClient cl;

  //the rest of it
}

In other words, what is Spring Boot equivalent of

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

I didn't find anything useful in documentation: https://docs.spring.io/spring-boot/docs/current/reference/html/common-application-properties.html

badbishop
  • 1,281
  • 2
  • 18
  • 38

2 Answers2

1

building webTestClient using current application context, no need to hardcode uri and port number

    @Autowired
    ApplicationContext context;

    @Autowired
    WebTestClient webTestClient;

    @Before
    public void setup() throws Exception {

        this.webTestClient = WebTestClient.bindToApplicationContext(this.context).build();
    }
jbaddam17
  • 277
  • 2
  • 10
0

You can use something like server.servlet.context-path=/myServletContextPath.

Daniel Atlas
  • 1
  • 2
  • 5
  • No, that sets the context path on the server side, but the client assumes it to be /. That's the whole point of posting the question. And I have tried it, of course. – badbishop Jun 06 '19 at 07:21
  • Did you happen to check the following link - https://stackoverflow.com/questions/48226651/cant-autowire-webtestclient-no-auto-configuration – Daniel Atlas Jun 06 '19 at 07:36
  • yes, even commented on it long ago. I'm not sure how is it relevant to my question. I get the same result with `@AutoConfigureWebTestClient` annotation as I get without it. – badbishop Jun 06 '19 at 08:32
  • Even though it is set in the server side, the client can still pick it up by declaring it: `@Value("${server.servlet.context-path:/defaultContext}") private String contextPath;` – Leslie Miller Jun 11 '21 at 02:28