我正在使用Espresso 2.2编写仪器测试.
流程我想测试:
>通过测试点击radioButton
> onClick启动对API的请求
>每次不同时间后我都会收到回复
>肯定响应触发在活动中调用的接口方法
> onRequestSuccess我在屏幕上创建名为vSetupAmount的其他面板可见
我想在点击radioButton后注册IdleResource,等待vSetupAmount变为可见.但我不能让它发挥作用.请告诉我我做错了什么.
我写过这样的IdleResource:
public class AmountViewIdlingResource implements IdlingResource { private CountriesAndRatesActivity activity; private ResourceCallback callback; private SetupAmountView amountView; public AmountViewIdlingResource(CountriesAndRatesActivity activity) { this.activity = activity; amountView = (SetupAmountView) this.activity.findViewById(R.id.vSetupAmount); } @Override public String getName() { return "Amount View idling resource"; } @Override public boolean isIdleNow() { callback.onTransitionToIdle(); return amountView.getVisibility() == View.VISIBLE; } @Override public void registerIdleTransitionCallback(ResourceCallback resourceCallback) { this.callback = resourceCallback; } }
所以我将活动传递给IdleResource,链接视图与变量.我知道IdleResource不会让测试通过,直到isIdleNow()返回值true.因此,如果视图是View.GONE,那么它将不会更进一步.
它在测试中看起来如何:
// click of radioButton picked from radioGroup onView(withId(rgDeliveries.getChildAt(id).getId())).perform(scrollTo(),click()); // wait for view to become visible Espresso.registerIdlingResources(new AmountViewIdlingResource(getActivity())); // go to button on view onView(withId(R.id.btnGetStarted)).perform(scrollTo()); // unregister idle resource for ( IdlingResource resource : getIdlingResources()) { Espresso.unregisterIdlingResources(resource); }
所以我点击了radioButton. IdleResource已成功注册但没有任何反应.在我的设备API响应来了.正在显示vSetupAmount但是
amountView.getVisibility() == View.VISIBLE;
这是永远被检查(但我在屏幕上看到我的视图)总是返回false.
我究竟做错了什么?
解决方法
我知道这可能为时已晚,但我的回答可能对某人有所帮助.
>当您实例化并注册AmountViewIdlingResource时,保留对它的引用并仅注销该引用,不要取消注册所有IdlingResources.
>如果您的空闲资源实际上并非每次都空闲,那么您的isIdleNow()方法实现应该只调用回调的onTransitionToIdle()方法.
我需要做类似的事情,等待按钮出现在屏幕上,这反过来只有在HTTP调用完成后才能看到.我对视图可见性空闲资源的实现如下:
public class ViewVisibilityIdlingResource implements IdlingResource { private final View mView; private final int mExpectedVisibility; private boolean mIdle; private ResourceCallback mResourceCallback; public ViewVisibilityIdlingResource(final View view,final int expectedVisibility) { this.mView = view; this.mExpectedVisibility = expectedVisibility; this.mIdle = false; this.mResourceCallback = null; } @Override public final String getName() { return ViewVisibilityIdlingResource.class.getSimpleName(); } @Override public final boolean isIdleNow() { mIdle = mIdle || mView.getVisibility() == mExpectedVisibility; if (mIdle) { if (mResourceCallback != null) { mResourceCallback.onTransitionToIdle(); } } return mIdle; } @Override public void registerIdleTransitionCallback(ResourceCallback resourceCallback) { mResourceCallback = resourceCallback; } }
希望这可以帮助