Unit Testing in Retrofit for Callback

后端 未结 1 1747
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-01-31 21:40

Here i got a sample of code in presenter. How do i make write a test for onSuccess and onFailure in retrofit call

public void getNotifications(final List

        
相关标签:
1条回答
  • 2021-01-31 22:33

    When you want to test different responses from service (API) it's probably best to mock it and return what you need.

        @Test
        public void testApiResponse() {
          ApiInterface mockedApiInterface = Mockito.mock(ApiInterface.class);
          Call<UserNotifications> mockedCall = Mockito.mock(Call.class);
    
          Mockito.when(mockedApiInterface.getNotifications()).thenReturn(mockedCall);
    
          Mockito.doAnswer(new Answer() {
            @Override
            public Void answer(InvocationOnMock invocation) throws Throwable {
              Callback<UserNotifications> callback = invocation.getArgumentAt(0, Callback.class);
    
              callback.onResponse(mockedCall, Response.success(new UserNotifications()));
              // or callback.onResponse(mockedCall, Response.error(404. ...);
              // or callback.onFailure(mockedCall, new IOException());
    
              return null;
            }
          }).when(mockedCall).enqueue(any(Callback.class));
    
          // inject mocked ApiInterface to your presenter
          // and then mock view and verify calls (and eventually use ArgumentCaptor to access call parameters)
        }
    
    0 讨论(0)
提交回复
热议问题