我试图用Robolectric和Mockito写一个单元测试。我有一个改造可观察的,我想用模拟回应进行测试。我尝试了link here
之类的东西但我得到了java.lang.NullPointerException
。这是我的代码示例:
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);
}
当我呼叫.subscribe(cb.capture())
时,出现空指针异常。
我以为我能够捕获subsribe()
内的调用并使用虚拟对象进行测试。我想我误解了一些东西,但不确定哪个部分:/。