Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring Test MockMvc perform request on external URL

I'm trying to perform a POST request on URL outside the current context, and it looks like Spring cannot understand it.

Test code:

        String content = mvc
            .perform(post("http://some-external-url.com:8080/somepath)
                    .header("Authorization", authorization)
                    .contentType(MediaType.APPLICATION_FORM_URLENCODED)
                    .param("username", username)
                    .param("password", password)
            .andExpect(status().isOk())
            .andReturn().getResponse().getContentAsString();

Works like a charm on current context. But remote service cannot be reached at all. It seems like "http://some-external-url.com:8080" part is ignored.

Mock creation code:

mvc = MockMvcBuilders.webAppContextSetup(context).build();

Is there any way to make it work? Because using standard Java HttpUrlConnection class is a huge pain.

like image 653
Mikhail Kholodkov Avatar asked Dec 29 '15 22:12

Mikhail Kholodkov


1 Answers

No. There is no way to make the Spring MVC Test Framework work with external servers (or any actual server for that matter).

As stated in the Spring Reference Manual,

The Spring MVC Test framework provides first class support for testing Spring MVC code using a fluent API that can be used with JUnit, TestNG, or any other testing framework. It’s built on the Servlet API mock objects from the spring-test module and hence does not use a running Servlet container.

The last sentence spells it out: Spring MVC Test does not use a running Servlet container. In fact, it cannot be used with a running Servlet container or any kind of actual server (local or remote).

As an alternative, if you must test against an external server, you could then consider using REST Assured instead of Spring MVC Test for those special cases.

like image 180
Sam Brannen Avatar answered Oct 23 '22 09:10

Sam Brannen