Junit 4发布新活动冻结测试

时间:2016-01-25 11:21:34

标签: java android junit4 android-testing android-espresso

我想测试我的LoginActivity使用Junit4和Espresso启动MainActivity,但是当执行登录时单击以启动MainActivity,它会冻结,点击后不会执行任何代码(在模拟器上打开MainActivity) 这是代码:

@RunWith(AndroidJUnit4.class)
@LargeTest
public class LoginActivityTest {

private static String TAG = "LoginActivityTest";
private static String phoneNumber = "xxxxxxxxx";
private static String password = "yyyyyy";
LoginActivity activity;

@Rule
public ActivityTestRule<LoginActivity> mActivityRule = new ActivityTestRule<>(LoginActivity.class);

@Before
public void getActivity() {
    activity = mActivityRule.getActivity();
}

@Test
public void checkIfLoginIsWorking() {
    Log.i(TAG, "Checking if login is working properly");
    Instrumentation.ActivityMonitor activityMonitor = InstrumentationRegistry.getInstrumentation().addMonitor(MainActivity.class.getName(), null, false);
    Assert.assertNotNull("Monitor null", activityMonitor);
    onView(withId(R.id.zone_button_continue)).perform(ViewActions.click());
    onView(withId(R.id.loginButton)).check(ViewAssertions.matches(ViewMatchers.isDisplayed()));
    onView(withId(R.id.number)).check(ViewAssertions.matches(ViewMatchers.isDisplayed()));
    onView(withId(R.id.password)).check(ViewAssertions.matches(ViewMatchers.isDisplayed()));
    onView(withId(R.id.number)).perform(ViewActions.typeText(phoneNumber));
    onView(withId(R.id.password)).perform(ViewActions.typeText(password));
    Log.i(TAG, "0");
    onView(withId(R.id.loginButton)).perform(ViewActions.click());
    Log.i(TAG, "1");
    MainActivity mainActivity = (MainActivity) activityMonitor.waitForActivity();
    //MainActivity mainActivity = (MainActivity) InstrumentationRegistry.getInstrumentation().waitForMonitor(activityMonitor); //Also tried. no luck
    //MainActivity mainActivity = (MainActivity) InstrumentationRegistry.getInstrumentation().waitForMonitorWithTimeout(activityMonitor, 5); //Also tried, no luck
    Assert.assertNotNull(mainActivity);
    mainActivity.finish();

}

@After
public void tearDown() throws Exception {
    try {
        Thread.sleep(2000);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
}

}

控制台打印出“检查登录是否正常工作”,“0”,点击后没有其他任何内容,测试在测试旁边的Android监视器中旋转“进度轮”一直持续一段时间。任何有关这方面的帮助将不胜感激!

我换了:

onView(withId(R.id.loginButton)).perform(ViewActions.click());

使用:

activity.runOnUiThread(new Runnable() {
        @Override
        public void run() {
            activity.findViewById(R.id.loginButton).performClick();
            Log.i(TAG, "1");
        }
    });

并且它解决了这个问题,但我对此并不十分满意,因为我认为Espresso处理所有线程并且会让我的生活更轻松,因为如果我想在新打开时执行一些点击或输入操作活动我必须再次调用 runOnUiThread 并在那里进行点击/输入/等。也许我误解了这个概念,或者我只是做错了什么。任何意见都将受到高度赞赏。

0 个答案:

没有答案