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 {
    @Mock
    private ApiClient apiClient;
    @Mock
    private UserApi userApi;

    @InjectMock
    private ApiUtils apiUtils;

    @Before
    public void setUp() {
       MockitoAnnotations.initMocks(this);
       apiUtils = new ApiUtils(apiClient);
    }

    @Test
    public void testSomething() {
       when(userApi.doSomething).thenReturn(myMock);
       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?

Answer

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 *