回调改造中的单元测试

时间:2017-07-18 07:18:31

标签: android unit-testing junit mockito retrofit2

这里我在演示者中获得了一些代码示例。如何在改装调用中为onSuccess和onFailure编写测试

public void getNotifications(final List<HashMap<String,Object>> notifications){

        if (!"".equalsIgnoreCase(userDB.getValueFromSqlite("email",1))) {
            UserNotifications userNotifications =
                    new UserNotifications(userDB.getValueFromSqlite("email",1),Integer.parseInt(userDB.getValueFromSqlite("userId",1).trim()));
            Call call = apiInterface.getNotifications(userNotifications);
            call.enqueue(new Callback() {
                @Override
                public void onResponse(Call call, Response response) {
                    UserNotifications userNotifications1 = (UserNotifications) response.body();


                    if(userNotifications1.getNotifications().isEmpty()){
                        view.setListToAdapter(notifications);
                        onFailure(call,new Throwable());
                    }
                    else {
                        for (UserNotifications.Datum datum:userNotifications1.getNotifications()) {
                            HashMap<String,Object> singleNotification= new HashMap<>();
                            singleNotification.put("notification",datum.getNotification());
                            singleNotification.put("date",datum.getDate());
                            notifications.add(singleNotification);
                        }
                        view.setListToAdapter(notifications);
                    }
                }

                @Override
                public void onFailure(Call call, Throwable t) {
                    call.cancel();
                }
            });
        }
    }

}

我如何编写单元测试来涵盖这段代码的所有情况。

由于

2 个答案:

答案 0 :(得分:20)

当您想要测试来自服务(API)的不同响应时,最好先模拟它并返回您需要的响应。

    @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)
    }

答案 1 :(得分:0)

对于那些使用 Kotlin 和 MockK 寻找答案的人:

假设你有这样的事情:

background-repeat: no-repeat; 

您可以使用 Junit 5 和 mockK 进行测试

class ApiService(private val client: OkHttpClient) {
    
    fun makeApiCall() {
        val url = "https://someendpoint.com.br/"
        val request = Request.Builder().url(url).build()
        client.newCall(request).enqueue(object : Callback {
            override fun onFailure(call: Call, exception: IOException) {
                //Logic to handle Failure
            }

            override fun onResponse(call: Call, response: Response) {
                //Logic to handle Success
            }
        })
    }
}