So I have two classes : A RestClient class and another MetadataService class which uses the restClient bean.
This is the RestClient class
public class RestClientConfig {
//actual class is more complex than this as we are authenticating with kerberos and there's
//code that generates kerberos token and injects it into the rest client builder
@Bean("customRestClient")
public RestClient restClient(RestClient.Builder builder) {
return builder.build();
}
}
Below is the service class
public class MetadataService {
@Autowired
@Qualifier("customRestClient")
RestClient customRestClient;
public void makeCall() {
try {
final String response = customRestClient.method(HTTPMethod.POST).uri("http://example.com")
.headers(getHeaders()).body(//some body here).retrieve()
.toEntity(String.class);
log.info(response);
}
}
}
Now I want to write a test class for MetadataService.
Things I have tried :
- Using @Mock annotation on the restClient bean but that lead to exceptions (more below)
- Using @RestClientTest on the class albeit there’s a lot of confusion on how I should use this.
Here is my test class which I have written so far (what I have referenced in #1)
public class MetadataServiceTest {
@Mock
RestClient customRestClient;
@InjectMock
MetadataService metadataService;
@Test
public void testMakeCall() {
when(customRestClient.method(HTTPMethod.POST).uri("http://example.com")
.headers(any()).body(any()).retrieve()
.toEntity(String.class)).thenReturn(response);
metadataService.makeCall();
}
}
This leads to exceptions like this one:
java.lang.NullPointerException: Cannot invoke “org.springframework.web.client.RestClient$RequestBodyUriSpec(String, Object[])” because the return value of “org.springframework.web.client.RestClient.method(org.springframework.http.HttpMethod)” is null