I have following implementation which uses RestTemplate to make request to external service:
@Component
public class ExternalProvider {
private ProviderProperties providerProperties;
@Autowired
@Qualifier("exprd")
private RestTemplate restTemplate;
@Bean
@Qualifier("exprd")
public RestTemplate restTemplate() {
return new RestTemplate();
}
@Autowired
public ExternalProvider(ProviderProperties providerProperties) {
this.providerProperties = providerProperties;
}
public String request(String requestParams) {
...
return restTemplate.getForObject(providerProperties.getUrl(), String.class);
}
}
And here is the test:
@ContextConfiguration(classes = {ExternalProviderTest.TestConfig.class})
@RunWith(SpringJUnit4ClassRunner.class)
public class ExternalProviderTest {
private ExternalProvider externalProvider;
private ProviderProperties providerProperties;
@TestConfiguration
static class TestConfig {
@Bean
@Qualifier("exprd")
public RestTemplate restTemplate() {
return new RestTemplate();
}
}
@Before
public void setUp() {
providerProperties = new ProviderProperties();
externalProvider = new ExternalProvider(providerProperties);
}
@Test
public void test_makeRequest() {
assertNotNull(externalProvider.request("params"));
}
}
My test above is not running because of a NullPointerException when restTemplate is null. It seems that the TestConfig I define in my test is ignored. Anyone has an idea what did I configure wrong here? Thank you!