0

I waned to redirect TestRestTemplate trough proxy. The difficult part for me is that I cannot create new TestRestTemplate because I am using it inside Spring Boot test so I have to use @Autowired.

@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
class DataImportRouteRestTest {

  @Autowired
  private TestRestTemplate testRestTemplate;

Inside test method I use it like that:

testRestTemplate.postForEntity("/camel/my/path", xml, String.class);

As you can see I don't specify host or port. It is done by @Autowired.

I tried to get help from here https://www.baeldung.com/java-resttemplate-proxy but I couldn't find anything useful. I also wanted to try RestTemplateCustomizer but then learned that there is no TestRestTemplateCustomizer and RestTemplateCustomizer cannot be used with TestRestTemplate.

So I ended up with following solution but since it's using reflection I would like to know if there are some better ways?

InterceptingClientHttpRequestFactory interceptingClientHttpRequestFactory = (InterceptingClientHttpRequestFactory)testRestTemplate.getRestTemplate().getRequestFactory();
Field privateField = InterceptingClientHttpRequestFactory.class.getSuperclass().getDeclaredField("requestFactory");
privateField.setAccessible(true);
SimpleClientHttpRequestFactory simpleClientHttpRequestFactory = (SimpleClientHttpRequestFactory)privateField.get(interceptingClientHttpRequestFactory);
Proxy proxy = new Proxy(Type.HTTP, new InetSocketAddress("localhost", 8080));
simpleClientHttpRequestFactory.setProxy(proxy);
u4963840
  • 81
  • 1
  • 8

0 Answers0