Android:Espresso:单击是阻止用户界面,无法进行下一步检查

时间:2019-04-16 08:33:32

标签: android android-espresso android-testing

我有按钮活动。单击此按钮时,我将显示特定的布局。 我要编写Espresso测试,以检查是否按按钮,然后显示特定的布局。 在这里测试:

@RunWith(AndroidJUnit4::class)
class AddTraderActivityTest {
    // The IntentsTestRule class initializes Espresso Intents before each test, terminates the host activity, and releases Espresso Intents after each test
    @get:Rule
    var addTraderActivity: IntentsTestRule<AddTraderActivity> = IntentsTestRule(AddTraderActivity::class.java)

@Test
fun allFieldsFill_buttonStart_click_progress_isDisplayed() {
    onView(withId(R.id.baseTextInputEditText))
        .perform(typeText(BASE_TEST))
    onView(withId(R.id.quoteTextInputEditText))
        .perform(typeText(QUOTE_TEST))

    onView(withId(R.id.startButton))
        .perform(click())

    // not execute while not finish click
    onView(withId(R.id.containerProgressBarLayout))
        .check(matches(isDisplayed()))
} 

问题是,先调用.perform(click())然后调用下一个方法

onView(withId(R.id.containerProgressBarLayout))
    .check(matches(isDisplayed()))

没有被呼叫click()的工作尚未完成时(单击按钮会启动HTTP请求)。在 N 秒后(请求完成后),Espresso继续执行并评估.check(matches(isDisplayed()

但是我需要检查单击按钮时是否显示了我的特定布局。

点击按钮的工具在这里。单击按钮后,由Retrofit 2发出 ASYNC http请求。完成后,请调用回调方法以获取结果。

 public void doClickStart(String base, String quote) {
        isHidekKeyboardLiveData.setValue(true);
        isShowProgressLiveData.setValue(true);
        TransportService.executeTraderOperation(Trader.Operation.CREATE, base.trim(), quote.trim(), new DefaultRestClientCallback<Void>() {
            @Override
            public void onSuccess(Response<Void> response) {
                isShowProgressLiveData.setValue(false);
                isForwardToTradersLiveData.setValue(true);
            }

            @Override
            public void onError(ErrorResponse errorResponse) {
                isShowProgressLiveData.setValue(false);
                String message = errorResponse.getMessage();
                messageLiveData.setValue(new SingleEvent(message));
            }
        });
    }

public static void executeTraderOperation(Trader.Operation traderOperation, String base, String quote, Callback<Void> callback) {
        TraderMonitorRestClient traderMonitorRestClient = RestClientFactory.createRestClient(TraderMonitorRestClient.class);
        String sender = BuildConfig.APPLICATION_ID + "_" + BuildConfig.VERSION_NAME;
        String key = DateUtil.getDateAsString(new Date(), "mmHHddMMyyyy");
        Call<Void> call = traderMonitorRestClient.executeTraderOperation(traderOperation.toString().toLowerCase(), base, quote, sender, key);
        // asynchronously
        call.enqueue(callback);
    }

在我的活动中,点击完成后,我将完成当前活动:

 addTraderViewModel.getIsForwardToTradersLiveData().observe(this, new Observer<Boolean>() {
            @Override
            public void onChanged(Boolean isForwardToTraders) {
                if (isForwardToTraders) {
                    setResult(RESULT_OK);
                    finish();
                }
            }
        });

这里是失败测试的结果:

$ adb shell am instrument -w -r   -e debug false -e class 'com.myproject.activity.AddTraderActivityTest#allFieldsFill_buttonStart_click_progress_isDisplayed' com.myproject.debug.test/androidx.test.runner.AndroidJUnitRunner
Client not ready yet..
Started running tests

java.lang.RuntimeException: No activities found. Did you forget to launch the activity by calling getActivity() or startActivitySync or similar?
at androidx.test.espresso.base.RootViewPicker.waitForAtLeastOneActivityToBeResumed(RootViewPicker.java:169)
at androidx.test.espresso.base.RootViewPicker.get(RootViewPicker.java:83)
at androidx.test.espresso.ViewInteractionModule.provideRootView(ViewInteractionModule.java:77)
at androidx.test.espresso.ViewInteractionModule_ProvideRootViewFactory.provideRootView(ViewInteractionModule_ProvideRootViewFactory.java:35)
at androidx.test.espresso.ViewInteractionModule_ProvideRootViewFactory.get(ViewInteractionModule_ProvideRootViewFactory.java:24)
at androidx.test.espresso.ViewInteractionModule_ProvideRootViewFactory.get(ViewInteractionModule_ProvideRootViewFactory.java:10)
at androidx.test.espresso.base.ViewFinderImpl.getView(ViewFinderImpl.java:62)
at androidx.test.espresso.ViewInteraction$2.call(ViewInteraction.java:276)
at androidx.test.espresso.ViewInteraction$2.call(ViewInteraction.java:268)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)

1 个答案:

答案 0 :(得分:0)

从您发布的错误代码中,您的Activity尚未开始进行测试。 使用以下代码模拟活动:

@get:Rule
var activityRule: ActivityTestRule<YourActivity> =
   ActivityTestRule(YourActivity::class.java)

(如果您需要向该活动传递参数):

@get:Rule
var activityRule: ActivityTestRule<YourActivity> =
   ActivityTestRule(YourActivity::class.java)

@Test
fun `test activity X`() {
   val intent = Intent()
   intent.putExtra("your_key", "your_value");
   activityRule.launchActivity(intent)
}