Sometimes you may want to use Retrofit2 and Spring framework in your test automation project when developing automated scripts to test web services.
It is up to you to decide if it is good or bad to use such ‘NOT-lightweight’ framework as Spring in you TAF but that’s completely another topic.
But if Spring + Retrofit is your case let’s take a look at Spring @PostConstruct annotation.
Regular code structure with Retrofit
Here’s an example of regular code structure when we’re using Retrofit.
First of all we have an interface with API endpoints:
And a class where you configure service builder:
But what if you have plenty of services and you want to generates an implementation of each service interface?
Here we can make use of @PostConstruct.
@PostConstruct - why to use?
Now we can modify code structure a bit and as a result we have ServiceBuilder.class, GitHubEndpoints
and TwitterEndpoints interfaces with endpoints and implementation classes GitHubService and TwitterService. Let’s take a look at each of these classes.
In ServiceBuilder.class we have following build() method:
And in ‘service’ classes we call build() passing the required class with endpoints. For instance,
So in this case we have simple and well-structured code.