我正在使用blog中提到的上述技术,但是我注意到它没有等待我尝试设置所需的15秒。我的问题是,如果所有后端任务在15秒之前完成,espresso会识别它并开始下一次连续操作吗?任何领导对此表示赞赏。
public class ElapsedTimeIdlingResource implements IdlingResource {
private final long startTime;
private final long waitingTime;
private ResourceCallback resourceCallback;
public ElapsedTimeIdlingResource(long waitingTime) {
this.startTime = System.currentTimeMillis();
this.waitingTime = waitingTime;
}
@Override
public String getName() {
return ElapsedTimeIdlingResource.class.getName() + ":" + waitingTime;
}
@Override
public boolean isIdleNow() {
long elapsed = System.currentTimeMillis() - startTime;
boolean idle = (elapsed >= waitingTime);
if (idle) {
resourceCallback.onTransitionToIdle();
}
return idle;
}
@Override
public void registerIdleTransitionCallback(
ResourceCallback resourceCallback) {
this.resourceCallback = resourceCallback;
}
}
==
long waitingTime = DateUtils.MINUTE_IN_MILLIS / 4;
IdlingPolicies.setMasterPolicyTimeout(
waitingTime * 2, TimeUnit.MILLISECONDS);
IdlingPolicies.setIdlingResourceTimeout(
waitingTime * 2, TimeUnit.MILLISECONDS);
IdlingResource idlingResource
= new ElapsedTimeIdlingResource(waitingTime);
Espresso.registerIdlingResources(idlingResource);
答案 0 :(得分:1)
您需要在registerIdlingResources()
之后运行Espresso命令,任何Espresso命令。我在自己的PC上创建了这个示例单元测试,它工作正常。
@RunWith(AndroidJUnit4.class)
public class ExampleInstrumentedTest {
@Rule public ActivityTestRule<MainActivity> rule = new ActivityTestRule<>(MainActivity.class);
private final long waitingTime = DateUtils.MINUTE_IN_MILLIS / 4;
@Before public void setUp() {
IdlingPolicies.setMasterPolicyTimeout(waitingTime * 2, TimeUnit.MILLISECONDS);
IdlingPolicies.setIdlingResourceTimeout(waitingTime * 2, TimeUnit.MILLISECONDS);
}
@Test public void useAppContext() throws Exception {
IdlingResource idlingResource = new ElapsedTimeIdlingResource(waitingTime);
Espresso.registerIdlingResources(idlingResource);
onView(withId(R.id.btnStart)).perform(click());
Espresso.unregisterIdlingResources(idlingResource);
assertTrue(true);
}
}
在我的示例中,我有一个名为btnStart
的按钮,我点击了该按钮,但它可以是与您的应用相关的任何内容。如果这对您有用,请告诉我。
并在评论中直接回答您的进一步问题:
isIdleNow()
进行轮询。当idle
为true
时,这是Espresso的信号,继续执行下一个命令。如果要阻止,则需要isIdleNow()
才能返回false
。ViewMatchers
,点击等内容),而不是任何其他线程。该活动将继续正常运作。