2017-07-18 55 views
0

在这里我得到了演示者代码示例。如何使在改造调用写的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(); 
       } 
      }); 
     } 
    } 

} 

我怎样写单元测试涵盖所有情况下,这段代码。

感谢

回答

4

当你想从服务(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) 
    } 
+0

三江源洙多猪头...它真的救了我的 – Jay

+0

天你能解释一下我关于Mockito.doAnswer(东西..) – Jay

+0

您使用符号指定仿制品的行为。它类似于Mockito.when(mockObject).someMethod(any(Parameter.class))。thenReturn(returnValue);但是这个必须用于没有(void)返回类型的函数。请参阅https://testing.googleblog.com/2014/03/whenhow-to-use-mockito-answer.html。 –