springspring-webclientwebtestclient

How to specify a specfic port number for Spring WebTestClient


I have a locally running rest endpoint I am attempting to communicate with using Spring WebClient. As a first step for testing purposes, I am trying to use Spring WebTestClient. My local rest endpoint runs on a specific port (lets say 8068). My assumption is that since the port is fixed, I am supposed to use:

SpringBootTest.WebEnvironment.DEFINED_PORT

, and then somehow specify what that port is in my code. However I do not know how to do that. It would appear to default to 8080. Here are the important parts of my code:

@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT)
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class SpringWebclientApplicationTests {

@Autowired
private WebTestClient webTestClient;

@Test
public void wcTest() throws Exception {

    String fullUri = "/services/myEndpoint/v1?userIds=jsmith&objectType=DEFAULT";

    WebTestClient.ResponseSpec responseSpec1 = webTestClient.get().uri(fullUri, "").exchange().expectStatus().isOk();
}

This test expects to return "200 OK", but returns "404 NOT_FOUND". The request shown in the error response is:

GET http://localhost:8080/services/myEndpoint/v1?userIds=jsmith&objectType=DEFAULT

, obviously because it defaults to 8080, and I need to it to be 8068. I woould be grateful to anyone who can explain to define the port properly. Thanks.


Solution

  • I figured it out. I don't believe you are supposed to use

    SpringBootTest.WebEnvironment.DEFINED_PORT
    

    unless the endpoint is listening on 8080. In my case, since I needed to use a port number I could not control, i did this instead:

    @RunWith(SpringRunner.class)
    @FixMethodOrder(MethodSorters.NAME_ASCENDING)
    public class SpringWebclientApplicationTests {
    
        private WebTestClient client;
    
        @Before
        public void setup() {
            String baseUri = "http://localhost:" + "8079";
            this.client = WebTestClient.bindToServer().baseUrl(baseUri).build();
        }
    
        @Test
        public void wcTest() throws Exception {
    
        String fullUri = "/services/myEndpoint/v1?userIds=jsmith&objectType=DEFAULT";
        WebTestClient.ResponseSpec responseSpec1 = client.get().uri(fullUri, "").exchange().expectStatus().isOk();
        }
    }
    

    , where I instantiate the webtestclient locally using the bindToServer method, and not as an autowired bean, and removing the:

    @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT)
    

    , so it works fine now.