5

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 :/ .

Community
  • 1
  • 1
fGab
  • 59
  • 4
  • Possible duplicate of [What is a NullPointerException, and how do I fix it?](http://stackoverflow.com/questions/218384/what-is-a-nullpointerexception-and-how-do-i-fix-it) – David Rawson Jan 28 '17 at 05:57
  • `Mockito.anyString()` is an ArgumentMatcher. You can't use it to make random values for your test. Besides, you also need to stub before you verify in your test. Please read the [tutorial for Mockito](http://site.mockito.org/) – David Rawson Jan 28 '17 at 05:59

0 Answers0