Mock swagger auto-generated api class

I have some API clients auto-generated by Swagger, for the sake of simplicity let’s say I have (these are auto-generated):

  • ApiClient <– This is the base client
  • UserApi <– This takes in ApiClient in it’s constructor

Now I have created a ApiUtils:

public class ApiUtils {
    private UserApi userApi;

    public ApiUtils(final ApiClient apiClient) {
        userApi = new UserApi(apiClient);

    // Methods here

I want to mock this class, and I was hoping that I could use InjectMethod for the UserApi. I tried the following:

public class ApiUtilsTest {
    private ApiClient apiClient;
    private UserApi userApi;

    private ApiUtils apiUtils;

    public void setUp() {
       apiUtils = new ApiUtils(apiClient);

    public void testSomething() {
       apiUtils.someMethodThatUsesApiUser ...

But because UserApi is initialized in the constructor of the Utils class, then my mock for it is not injected.

How can I mock this?


I’ve created a simple library which supports mocking Swagger-generated stubs as service endpoints (on a local port) using Mockito.

The implementation flavour and code-generation settings will affect whether things will work, but at least this is a starting point. Feel free to file issues and/or PRs for supporting your use-case.

Leave a Reply

Your email address will not be published. Required fields are marked *