我正在创建Android应用程序。我正在使用Espresso进行测试。
我有一个方法活动:
public void render(Recipe recipe){
//draw the recipe to the activity
}
我想测试一下这种方法是否正常工作。
无效解决方案1
我测试了以下
@Test
public void viewPaintsRecipes() {
final Activity activity = activityRule.launchActivity(new Intent());
((MainActivity)activity).render(Arrays.asList(new Recipe[]{recipe}));
onView(withId(R.id.text)).check(matches(withText(recipe.toString())));
}
我得到了一个例外。
只有创建视图层次结构的原始线程才能触及它 视图。
无效解决方案2
我还尝试将两行放在主线程中由Handler运行的runnable中,但测试挂起。
我怎么能取消这个?
备注
我附上了完整的测试。请注意,我也使用dagger和Mockito。
@RunWith(AndroidJUnit4.class)
@LargeTest
public class MainActivityTestWithMockPresenter {
Recipe recipe = new Recipe("sampleTitle");
@Rule
public ActivityTestRule<MainActivity> activityRule = new ActivityTestRule(MainActivity.class, true, false);
@Mock
MainActivityPresenter mockPresenter;
@Mock
AndroidApplication mockContext;
@Before
public void insertMockedComponent(){
MockitoAnnotations.initMocks(this);
Instrumentation instrumentation = InstrumentationRegistry.getInstrumentation();
AndroidApplication app = (AndroidApplication) instrumentation.getTargetContext().getApplicationContext();
MyModule mockedMyModule = new MyModule(mockContext){
@Provides
public MainActivityPresenter getMainActivityPresenter(){
return mockPresenter;
}
};
MyComponent component = DaggerMyComponent.builder().myModule(mockedMyModule).build();
app.setComponent(component);
}
@Test
public void viewPaintsRecipes() {
final Activity activity = activityRule.launchActivity(new Intent());
((MainActivity)activity).render(Arrays.asList(new Recipe[]{recipe}));
onView(withId(R.id.text)).check(matches(withText(recipe.toString())));
}
}
由于
答案 0 :(得分:8)
我已设法在我的build.gradle
文件中使用这些依赖项:
androidTestCompile 'com.android.support:support-annotations:23.1.0'
androidTestCompile 'com.android.support.test:runner:0.4.1'
androidTestCompile 'com.android.support.test:rules:0.4.1'
androidTestCompile 'org.hamcrest:hamcrest-library:1.3'
androidTestCompile 'com.android.support.test.espresso:espresso-core:2.2.1'
您需要使用ActivityTestRule.runOnUiThread(@NotNull java.lang.Runnable runnable)
方法,如下所示:
@Test
public void testRecipeRender() throws Throwable {
// When.
activityTestRule.runOnUiThread(new Runnable() {
@Override
public void run() {
activityTestRule.getActivity().render(someRecipe);
}
});
// Then.
// assert stuff about the recipe rendering here
}