java 使用Espresso进行测试时要使用的改装API包装器

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java 使用Espresso进行测试时要使用的改装API包装器相关的知识,希望对你有一定的参考价值。

public class TestBase extends ActivityInstrumentationTestCase2<Activity> {

    @Inject IdlingApiWrapper           idlingApiWrapper;
    @Inject IdlingDownloaderWrapper    downloader;
    @Inject Navigator                  navigator;
    @Inject Locale                     locale;
    @Inject MockRestAdapter            mockAdapter;
    @Inject MockApi                    api;

    protected Activity activity;

    public TestBase() {
        super(Activity.class);
    }

    @Override
    public void setUp() throws Exception {
        super.setUp();
        activity = getActivity();

        activity
            .getObjectGraph()
            .plus(new TestModule())
            .inject(this);

        Espresso.registerIdlingResources(idlingApiWrapper, downloader);

        mockAdapter.setDelay(50);
        mockAdapter.setErrorPercentage(0);
        mockAdapter.setVariancePercentage(0);
    }


    protected void screenshot(String description) throws Throwable{
        Thread.sleep(100);
        Spoon.screenshot(activity, description.replaceAll("[^a-zA-Z0-9_-]", "_"));
    }

    @dagger.Module(
        complete = false,
        library = true,
        injects = {
            TestBase.class,
            PreOrderCalendarTest.class,
            PreOrderParticipantSelectorTest.class
        }
    ) class TestModule {}
}
/**
 * Retrofit Api wrapper to be used when testing
 * with Espresso. See:
 * https://code.google.com/p/android-test-kit/wiki/EspressoSamples#Using_registerIdlingResource_to_synchronize_with_custom_resource
 */
public class IdlingApiWrapper implements Api, IdlingResource {

    private final Api           api;
    private final AtomicInteger counter;
    private final Handler       uiThreadHandler;

    private final List<ResourceCallback> callbacks;

    public IdlingApiWrapper(Application app, Api api) {
        this.api = api;
        this.callbacks = new ArrayList<>();
        this.counter = new AtomicInteger(0);
        this.uiThreadHandler = new Handler(app.getMainLooper());
    }

    @Override public void getPersonalOffers(Callback<OfferListResponse> callback) {
        counter.incrementAndGet();
        api.getPersonalOffers(wrapCallback(callback));
    }

    @Override public void getCategories(Callback<RootCategoryListResponse> callback) {
        counter.incrementAndGet();
        api.getCategories(wrapCallback(callback));
    }

    @Override public void getOfferDates(@Path("offerId") int offerId, Callback<OfferDateListResponse> callback) {
        counter.incrementAndGet();
        api.getOfferDates(offerId, wrapCallback(callback));
    }

    @Override public void getOfferCategory(@Path("categoryId") int categoryId, Callback<OfferListResponse> callback) {
        counter.incrementAndGet();
        api.getOfferCategory(categoryId, wrapCallback(callback));
    }

    private <T> Callback<T> wrapCallback(final Callback<T> callback) {
        return new Callback<T>() {
            @Override public void success(final T result, final Response response) {
                uiThreadHandler.post(new Runnable() {
                    @Override public void run() {
                        counter.decrementAndGet();
                        callback.success(result, response);
                        notifyIdle();
                    }
                });
            }

            @Override public void failure(final RetrofitError error) {
                uiThreadHandler.post(new Runnable() {
                    @Override public void run() {
                        counter.decrementAndGet();
                        callback.failure(error);
                        notifyIdle();
                    }
                });
            }
        };
    }

    @Override public String getName() {
        return this.getClass().getName();
    }

    @Override public boolean isIdleNow() {
        return counter.get() == 0;
    }

    @Override public void registerIdleTransitionCallback(ResourceCallback resourceCallback) {
        callbacks.add(resourceCallback);
    }

    private void notifyIdle() {
        if (counter.get() == 0) {
            for (ResourceCallback cb : callbacks) {
                cb.onTransitionToIdle();
            }
        }
    }
}
@Module(
    complete = false,
    library = true,
    overrides = true
)
public final class DebugApiModule {

    @Provides @Singleton ApiEndpoint provideApiEndpoint(Locale locale, @ApiEndpointMarker StringPreference apiEndpoint,
                                                        @NetworkIgnoreLocale BooleanPreference ignoreLocale) {
        return (ignoreLocale.get())
            ? ApiEndpoint.from(apiEndpoint.get())
            : ApiEndpoint.from(locale);
    }

    @Provides @Singleton MockRestAdapter provideMockRestAdapter(RestAdapter restAdapter, SharedPreferences preferences) {
        MockRestAdapter mockRestAdapter = MockRestAdapter.from(restAdapter);
        AndroidMockValuePersistence.install(mockRestAdapter, preferences);
        return mockRestAdapter;
    }

    @Provides @Singleton IdlingApiWrapper provideIdlingApiWrapper(Application app, RestAdapter restAdapter,
                                                                                      MockRestAdapter mockRestAdapter,
                                                                                      @IsMockMode boolean isMockMode,
                                                                                      MockApi mockApi) {
        return new IdlingApiWrapper(app, (isMockMode)
                ? mockRestAdapter.create(Api.class, mockApi)
                : new CachingApi(restAdapter.create(Api.class))
        );
    }

    @Provides @Singleton Api provideApi(IdlingApiWrapper wrapper) {
        return wrapper;
    }
}

以上是关于java 使用Espresso进行测试时要使用的改装API包装器的主要内容,如果未能解决你的问题,请参考以下文章

在Android Studio环境下使用ESPRESSO 测试框架进行UI测试

java 在Android Espresso测试中使用屏幕机器人

java 在Android测试中如何使用espresso-intents的示例

Appium v​​s Espresso 用于自动化测试框架

在ANDROID STUDIO环境下使用ESPRESSO 测试框架进行UI测试

Android自动化测试--Espresso框架使用