13

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.

Mikhail Kholodkov
  • 23,642
  • 17
  • 61
  • 78
  • Why are you expecting that MockMvc would work on external URLs? – chrylis -cautiouslyoptimistic- Dec 29 '15 at 22:57
  • 1
    Why not? It's just a testing tool, right?. To test my controller properly at first I should get some information from external web-service. I don't think it's very rare case. – Mikhail Kholodkov Dec 29 '15 at 23:08
  • 1
    It's a testing tool that very specifically emulates a small, isolated section of the Servlet stack. There's no HTTP client involved anywhere, and only part of an HTTP server. You might as well say that since Selenium is a testing tool, it should modify database schema. – chrylis -cautiouslyoptimistic- Dec 29 '15 at 23:10
  • Just a friendly note that if you find one of the answers to your question acceptable, feel free to [accept it](http://stackoverflow.com/help/accepted-answer) if you want to. – Sam Brannen Sep 10 '16 at 11:42

2 Answers2

16

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.

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
Sam Brannen
  • 29,611
  • 5
  • 104
  • 136
1

You can use new RestTemplate().getForObject("http://some-external-url.com:8080/somepath", String.class)

Harun
  • 667
  • 7
  • 13