我使用 Mockito、Robolectric 和 Hamcrest 库测试了我的 Retrofit 回调。
首先,在你的模块的 build.gradle 中设置 lib 栈:
dependencies {
testCompile 'org.robolectric:robolectric:3.0'
testCompile "org.mockito:mockito-core:1.10.19"
androidTestCompile 'org.hamcrest:hamcrest-library:1.1'
}
在 jour 项目的全局 build.gradle 中添加以下行到 buildscript 依赖项:
classpath 'org.robolectric:robolectric-gradle-plugin:1.0.1'
然后在 Android Studio 中进入“Build Variants”菜单(要快速找到它,按 Ctrl+Shift+A 并搜索它),并将“Test Artifact”选项切换为“Unit Tests”。 Android Studio 会将您的测试文件夹切换到“com.your.package (test)”(而不是 androidTest)。
好的。设置完成,是时候写一些测试了!
假设您有一些改造 api 调用来检索需要放入 RecyclerView 等适配器的对象列表。我们想测试适配器是否在成功调用时填充了正确的项目。
为此,我们需要切换您的 Retrofit 接口实现,您可以使用该接口通过模拟进行调用,并利用 Mockito ArgumentCaptor 类进行一些虚假响应。
@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<YourObject>>> callbackArgumentCaptor;
@Before
public void setUp() {
MockitoAnnotations.initMocks(this);
ActivityController<MainActivity> controller = Robolectric.buildActivity(MainActivity.class);
mainActivity = controller.get();
// Then we need to swap the retrofit api impl. with a mock one
// I usually store my Retrofit api impl as a static singleton in class RestClient, hence:
RestClient.setApi(mockRetrofitApiImpl);
controller.create();
}
@Test
public void shouldFillAdapter() throws Exception {
Mockito.verify(mockRetrofitApiImpl)
.getYourObject(callbackArgumentCaptor.capture());
int objectsQuantity = 10;
List<YourObject> list = new ArrayList<YourObject>();
for(int i = 0; i < objectsQuantity; ++i) {
list.add(new YourObject());
}
callbackArgumentCaptor.getValue().success(list, null);
YourAdapter yourAdapter = mainActivity.getAdapter(); // Obtain adapter
// Simple test check if adapter has as many items as put into response
assertThat(yourAdapter.getItemCount(), equalTo(objectsQuantity));
}
}
通过右键单击测试类并点击运行来继续测试。
就是这样。我强烈建议使用 Robolectric(带有 robolectric gradle 插件)和 Mockito,这些库使测试 android 应用程序变得更加容易。
我从下面的blog post 学到了这个方法。另请参阅this answer。
更新:如果您正在使用 Retrofit 和 RxJava,请查看 my other answer on that。