jeudi 19 novembre 2015

Android Unit Test with Retrofit/RxJava/Roboletric and Mockito

I'm trying to write a Unit test with Robolectric and Mockito. I've a retrofit observable and I would like to test with a mock response. I've tried something like that link here

but I got a java.lang.NullPointerException. Here a sample of my code:

 private MainActivity mainActivity;

  @Mock
  private FoursquareCalls mockApi;

  @Captor
  private ArgumentCaptor<Action1<FoursquareListResponse>> cb;

 @Before
  public void setup() {
    MockitoAnnotations.initMocks(this);

    ActivityController<MainActivity> controller = Robolectric.buildActivity(MainActivity.class);
    mainActivity = controller.get();

    controller.create();
  }


@Test
  public void shouldFillAdapterWithReposFromApi() throws Exception {
    mockApi.getListFoodTrucks(Mockito.anyString(), Mockito.anyString(), Mockito.anyString(),
        Mockito.anyString(), Mockito.anyString(), Mockito.anyString());

    Mockito.verify(mockApi).getListFoodTrucks(Mockito.anyString(), Mockito.anyString(), Mockito
        .anyString(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString())
        .subscribe(cb.capture());

    SearchFragment searchFragment = (SearchFragment) mainActivity.getFragmentManager().findFragmentById(R.id
        .fragment_container);

    FoursquareListResponse testRespo = new FoursquareListResponse();
    testRespo.foodtruckReponse = new FoodTruckResponseModel();
    testRespo.foodtruckReponse.listFoodtruck = new ArrayList<>();
    testRespo.foodtruckReponse.listFoodtruck.add(new FoodTruckResponseModel());
    testRespo.foodtruckReponse.listFoodtruck.add(new FoodTruckResponseModel());



    cb.getValue().call(testRespo);
    assertEquals(searchFragment.getAdapter(), 2);
  }

The Null pointer exception is appearing when I'm calling .subscribe(cb.capture()). I thought that I would be able to capture the call inside the subsribe() and do my test with a dummy object. I think I misunderstood something but not quiet sure which part :/ .

Aucun commentaire:

Enregistrer un commentaire