使用Roboletric进行改造单元测试

时间:2016-01-26 10:52:29

标签: unit-testing mockito retrofit robolectric

是否有可能测试Retrofit回调是否会成功返回?

我的代码非常简单:

@Config(constants = BuildConfig.class, sdk = 21,
            manifest = "app/src/main/AndroidManifest.xml")
@RunWith(RobolectricGradleTestRunner.class)
public class RetrofitCallTest {

private MainActivity mainActivity;

@Mock
private RetrofitApi mockRetrofitApiImpl;

@Captor
private ArgumentCaptor<Callback<List<MyObject>>> callbackArgumentCaptor;

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

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

    RestClient.setApi(mockRetrofitApiImpl);

    controller.create();
}

@Test
public void shouldFillAdapter() throws Exception {
    Mockito.verify(mockRetrofitApiImpl)
        .getYourObject(callbackAgrumentCaptor.capture());

    int objectsQuantity = 10;
    List<MyObject> list = new ArrayList<YourObject>;
    for(int i = 0; i < objectsQuantity; ++i) {
        list.add(new MyObject());
    }

    callbackArgumentCaptor.getValue().success(list, null);

    ListAdapter adapter = mainActivity.getAdapter(); 
    assertThat(adapter .getItemCount(), equalTo(objectsQuantity));
}

很清楚 - 当api返回成功时,我测试我的代码是否正常工作。

但有没有可能测试IF api返回成功?

0 个答案:

没有答案