I have a method that makes an API Call after 1 sec. I use Handler.postdelayed to implement this. Now I am trying to verify if the API call is being made with a unit test.
@Mock
private PlanRepository planRepository;
@Mock
private CreatePlanContract.View view;
private CreatePlanContract.Presenter presenter;
@Captor
private ArgumentCaptor<ListResponseCallback<IntersectingList>> listCaptor;
....
@Before
public void setUp() {
MockitoAnnotations.initMocks(this);
presenter = new CreatePlanPresenter(resourceProvider, sessionContext, planRepository);
presenter.start();
presenter.setView(view);
...
}
@Test
public void testOnCameraIdleGetListEnabled(){
presenter.onCameraIdle(true);
verify(planRepository,times(1))
.getList(listCaptor.capture());
}
This is the method in presenter that I want to test:
class PlanPresenter implements PlanContract.Presenter{
private Handler mHandler = new Handler();
private Runnable mRunnable = this::fetchList;
private WeakReference<CreatePlanContract.View> createPlanView;
private ListResponseCallback<IntersectingList> listListener = new ListResponseCallback<Intersectinglist>() {
@Override
public void onSuccess(@NonNull List<IntersectingList> list) {
Log.d(TAG, "callback: success resp came");
if(createPlanView.get() != null)
createPlanView.get().renderList(list);
}
@Override
public void onError(int i, @NonNull String s, @NonNull APIResponseBody apiResponseBody, @Nullable Exception e) {
Log.d(TAG, "callback: error resp came Auth");
}
};
@Override
public void start() {
//some initilizations
}
@Override
public void setView(@NonNull CreatePlanContract.View view) {
this.createPlanView = new WeakReference<>(view);
}
@Override
public void onCameraIdle(){
mHandler.postDelayed(mRunnable,1000);
}
private void fetchList(){
//this the method to be verified
planRepository.getList(listListener);
}
}
But since the api call is being made after 1 sec, the test is failing.
What I have tried: I tried following this link and use doAnswer() but I was unsuccessful. I thought of using thread.sleep() which seems like an awful approach for this problem(also read that its a bad approach)
PS: I am a noob to testing. I am using JUnit 4 and mockito