So I have a class that holds a bunch of methods(migrated from another project) that are suppose hit a REST API,but I don’t know if they are working correctly.I want to create a driver class that i can run manually to test these methods.
For example, I have a get() method that hits the actual REST API, but how would I test the inner meat of the method like if it is building the query parameter correctly, etc. I was thinking of a test driver class that returns the the status code and then the object since it will hit the actual endpoint. Any thoughts? and ideas
Example of class get()
public Object get(String endpointName, String id) {
UriBuilder uriBuilder = uriBuilder().path(DataConstants.PATH_GET);
uriBuilder.queryParamIfPresent(GET_PARAM_ENDPOINT_NAME, optionalString(endpointName));
uriBuilder.path(requiredPath(GET_PARAM_ID, id));
try {
String url = uriBuilder.build().toURL().toString();
String accessToken = this.clientHelper.accessToken();
ResponseEntity<String> result = HttpHelper.get(url, accessToken);
return this.fromJsonString(result.getBody(), new TypeReference<Object>() {});
} catch (MalformedURLException e) {
log.error(e.getLocalizedMessage(), e);
}
return null;
}
I was thinking of a test driver class that returns the the status code and then the object since it will hit the actual endpoint. Any thoughts? and ideas
You could use a mock server to provide real REST endpoints but as mocks. I usually use MockServer for this, it allows you to setup expectations (endpoints), define answers for certain request and verify that certain requests have been made.
There are some alternatives for this, I didn’t check them as I was satisfied with MockServers abilities.
You could also use a declarative REST client like OpenFeign where you write interfaces, annotate them and the implementation of the REST-client is then autogenerated at runtime.
Your code would look something like
interface RestApi {
@RequestLine("GET /path/to/object/{id}?{endpointName}")
Object getObject(@Param("endpointName") String endpointName, @Param("id") String id);
}
With some glue code e.g. for specifying a mapper for requests and answers, configuring authentication and host, etc. you can then be more on the safe side to have a working REST client. Better read- and maintainable also.
Still some integration tests can help.
OpenFeign is also included in Spring Boot as Spring Cloud OpenFeign with some adapted annotations etc. to fit better inside the Spring Boot landscape.