Mat*_*teu 8 testing android mockito android-espresso dagger-2
我正在创建Android应用程序.我正在使用Espresso进行测试.
我有一个方法的活动:
public void render(Recipe recipe){
//draw the recipe to the activity
}
Run Code Online (Sandbox Code Playgroud)
我想测试这个方法是否正常工作.
不工作的解决方案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())));
}
Run Code Online (Sandbox Code Playgroud)
我得到一个例外.
只有创建视图层次结构的原始线程才能触及其视图.
不工作的解决方案2
我还尝试将两行放在主线程中由Handler运行的runnable中,但测试挂起.
我该怎么做到这一点?
笔记
我附上了完整的测试.请注意,我也使用匕首和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())));
}
}
Run Code Online (Sandbox Code Playgroud)
谢谢
我已经设法在我的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'
Run Code Online (Sandbox Code Playgroud)
您需要使用以下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
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5719 次 |
| 最近记录: |