0

I want to create a test with a subdomain call, but it is not working, I'm getting this exception:

org.springframework.web.client.ResourceAccessException: I/O error on GET request for "http://test.localhost:4081/test": test.localhost; nested exception is java.net.UnknownHostException: test.localhost
    at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:744)
...
Caused by: java.net.UnknownHostException: test.localhost
at java.net.Inet6AddressImpl.lookupAllHostAddr(Native Method)
at java.net.InetAddress$2.lookupAllHostAddr(InetAddress.java:928)
at java.net.InetAddress.getAddressesFromNameService(InetAddress.java:1323)
...

Calling only localhost without subdomain works and calling localhost with subdomain using external tool (rest api tester) is also working. I tried to use IPv4 stack (-Djava.net.preferIPv4Stack=true), but I got the same exception. Do I need to set something to get it working? The test looks like this (the code is simplified):

@RunWith(SpringRunner.class)
@SpringBootTest(classes = {...}, webEnvironment=SpringBootTest.WebEnvironment.RANDOM_PORT)
@ActiveProfiles("test")
public class SubdomainTest {

    @Autowired
    private RestTemplateBuilder restTemplateBuilder;

    private int localPort;

    @Override
    public void onApplicationEvent(final ServletWebServerInitializedEvent event) {
        localPort = event.getWebServer().getPort();
    }

    @Test
    public void subdomainTest() throws Exception {
        MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
        converter.setSupportedMediaTypes(
                Arrays.asList(new MediaType[]{MediaType.APPLICATION_JSON, MediaType.APPLICATION_OCTET_STREAM}));
        TestRestTemplate restTemplate = new TestRestTemplate(
                restTemplateBuilder.rootUri("http://test.localhost:"+localPort).additionalMessageConverters(converter)
                , "test"
                , "test");
        ResponseEntity<String> response = restTemplate.getForEntity("/test", String.class); // throws exception
    }

}

Michal
  • 614
  • 8
  • 20

1 Answers1

0

I found a partial solution - add it to hosts file (Windows)

127.0.0.1   test.localhost

But this makes the test setup more complicated for my colleagues... It would be great to have it OS independent.

Michal
  • 614
  • 8
  • 20
  • You can only call a subdomain that actually exists, otherwise you will just have to use localhost in your code instead of test.localhost – Mark Rotteveel Nov 04 '20 at 14:32
  • I'm just curious, because browsers and http testing tools are able to deal with local subdomains without any change in hosts file. – Michal Nov 05 '20 at 17:10
  • That would indicate that those tools do their own fallback logic by (recursively?) stripping of the subdomains and trying again. Java only does a lookup of the domain provided, and if neither the hosts file or the DNS returns an IP address, it will fail. – Mark Rotteveel Nov 05 '20 at 19:06