Skip to content

Instantly share code, notes, and snippets.

@justin-lyon
Last active October 6, 2020 20:48
Show Gist options
  • Save justin-lyon/1c64017f4cb4cb9730213aec7905f159 to your computer and use it in GitHub Desktop.
Save justin-lyon/1c64017f4cb4cb9730213aec7905f159 to your computer and use it in GitHub Desktop.
Trying to test some stuff
@Configuration
public class RestTemplateConfiguration {
public static final String REST_TEMPLATE_NAME = "someRestTemplate";
@Autowired
private AppConfig appConfig;
@Value("${props.useProxy})
private boolean useProxy;
@Bean(name = REST_TEMPLATE_NAME)
public RestTemplate restTemplate(RestTemplateBuilder builder) {
return builder
.rootUri("")
.requestFactory(this::getHttpClientFactory) // -> NPE Here
.interceptors(getInterceptors())
.errorHandler(getErrorHandlers())
.build()
}
@Bean
public HttpComponentsClientHttpRequestFactory getHttpClientFactory() {
HttpComponentsClientHttpRequestFactory reqFactory = new HttpComponentsClientHttpRequestFactory();
// ...does some SSL / Proxy stuff
return reqFactory;
}
}
@RunWith(SpringJUnit4ClassRunner.class)
public class RestTemplateConfigurationTest {
@InjectMocks
private RestTemplateConfiguration templateConfig;
@Mock
@Qualifier(RestTemplateConfiguration.REST_TEMPLATE_NAME)
private RestTemplateBuilder builder;
@BeforeEach
public void setup() {
initMocks(this);
}
@Test
public void makeRequest_givenCustomHttpClientFactory_shouldRespondOK {
RestTemplate template = new RestTemplateBuilder()
.requestFactory(this.templateConfig::getHttpClientFactory)
.build()
ResponseEntity<String> response = null;
boolean caughtException = false;
try {
response = template.exchange("https://google.com", HttpMethod.GET, null, String.class);
} catch(Exception e) {
caughtException = true;
}
assertEquals(false, caughtException, "Should not have exception");
assertEquals(HttpStatus.OK, response.getStatusCode(), "Status should be OK.");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment