java Android - 如何使用IdlingResource等待JUnit断言的异步操作(可能是Observables或EvenBus)。

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java Android - 如何使用IdlingResource等待JUnit断言的异步操作(可能是Observables或EvenBus)。相关的知识,希望对你有一定的参考价值。

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

  @Test
  public void loginSucceed() {
    EventBusIdlingResource eventBusIdlingResource = new EventBusIdlingResource();
    registerIdlingResources(eventBusIdlingResource);
  
    click(R.id.button_login);
  
    IdlingResourceSleeper.sleep(eventBusIdlingResource);
  
    Customer customer = Customer.getCurrentObservable().toBlocking().first();
    assertThat(customer.getSession()).isNotNull()
  
    unregisterIdlingResources(eventBusIdlingResource);
  }
  
}
import android.support.test.espresso.IdlingResource;

/**
 * Have functions to sleep the processor because assertions are not linked to
 * {@link IdlingResource} to do assertions, so should be used before asserts if there's an
 * idle process.
 */
public class IdlingResourceSleeper {

    private static final int SLEEPS_LIMIT = 50;
    private static final int SLEEPS_TIME = 10;

    /**
     * Used to sleep {@link IdlingResourceSleeper#SLEEPS_LIMIT} times and
     * {@link IdlingResourceSleeper#SLEEPS_TIME} ms until idlingResource.isIdleNow() is false.
     *
     * @param idlingResource
     */
    public static void sleep(IdlingResource idlingResource) {
        int sleeps = 0;
        while (!idlingResource.isIdleNow() || sleeps < SLEEPS_LIMIT) {
            android.os.SystemClock.sleep(SLEEPS_TIME);
            sleeps++;
        }

    }
}
public class EventBusIdlingResource implements IdlingResource {

    private boolean busUpdated;

    public EventBusIdlingResource() {
        busUpdated = false;
        Bus.getInstance().register(this);
    }

    @Override
    public boolean isIdleNow() {
        if (busUpdated) {
            Bus.getInstance().unregister(this);
        }

        return busUpdated;
    }

    public void onEvent(OrderUpdatedEvent event) {
        busUpdated = true;
    }

    public void onEvent(SecondLapseEvent event) {
        busUpdated = true;
    }

    public void onEvent(ValidationCodeEvent event) {
        busUpdated = true;
    }

}

以上是关于java Android - 如何使用IdlingResource等待JUnit断言的异步操作(可能是Observables或EvenBus)。的主要内容,如果未能解决你的问题,请参考以下文章

如何使用 android-json-rpc 进行 Android(客户端)/Java(服务器)设置?

如何在Android平台上使用JS直接调用Java方法

如何使用 java/android 从 Firebase ONCE 读取数据?

如何在 java (Android) 上使用字符串

如何在Java(Android)中使用getMonth添加前导零[重复]

如何在android中使用java.nio.file包? [复制]