Как разрешить занятую работу потока в эспрессо - PullRequest
4 голосов
/ 27 мая 2019

Я пытаюсь протестировать индикатор прогресса приложения, который показывает неопределенный индикатор прогресса, пока модель представления извлекает данные.

Чтобы проверить это, я издеваюсь над поставщиком, который возвращаетданные и блокируют их до тех пор, пока мой тест не даст понять, что нужно идти дальше.Базовая настройка выглядит следующим образом:

@Test
public void testProgressIndicator() {
    injectProvider(mockProvider);
    startTestActivity();

    // The mock provider now runs on a worker thread and won't finish
    // until we tell it to.

    // We should now see a progress indicator.
    onView(withId(R.id.progress_indicator)).check(
        matches(withEffectiveVisibility(Visibility.VISIBLE)));

    // Tell the worker thread to finish up.
    mockProvider.setResult();

    // The worker thread now returns a result, the progress indicator
    // should be gone.
    onView(withId(R.id.progress_indicator)).check(
        matches(withEffectiveVisibility(Visibility.GONE)));
}

Этот код устарел, поэтому поставщик использует код блокировки в рабочем потоке, используя AsyncTask.

Однако Espresso обычно ожидает всехрабочие должны закончить, чтобы убедиться, что результаты не зависят от сроков.В частности, он использует AsyncTaskPoolMonitor для ожидания всех ожидающих AsyncTask объектов.Обычно это замечательно, но в моем случае я хочу, чтобы этот поток оставался занятым, пока эспрессо продолжается.Как я могу сказать Espresso не ждать эту конкретную тему?

Дешевый отговорка - это просто Thread и общение через Handler или что-то подобное, но было бы неплохо найтирешение при сохранении настройки с использованием AsyncTask.

Когда я врываюсь в отладчик, я вижу, что поток моего тестового бегуна застревает на первом check():

wait:-1, Object (java.lang)
parkFor$:2137, Thread (java.lang)
park:358, Unsafe (sun.misc)
park:190, LockSupport (java.util.concurrent.locks)
await:2059, AbstractQueuedSynchronizer$ConditionObject (java.util.concurrent.locks)
take:442, LinkedBlockingQueue (java.util.concurrent)
gatherAnyResult:83, InteractionResultsHandler (androidx.test.espresso)
gatherAnyResult:52, InteractionResultsHandler (androidx.test.espresso)
waitForAndHandleInteractionResults:314, ViewInteraction (androidx.test.espresso)
check:300, ViewInteraction (androidx.test.espresso)
testProgressIndicator:76, MyFragmentTest (com.my.test)  <<< ***********************
invoke:-1, Method (java.lang.reflect)
runReflectiveCall:50, FrameworkMethod$1 (org.junit.runners.model)
run:12, ReflectiveCallable (org.junit.internal.runners.model)
invokeExplosively:47, FrameworkMethod (org.junit.runners.model)
evaluate:17, InvokeMethod (org.junit.internal.runners.statements)
evaluate:80, RunBefores (androidx.test.internal.runner.junit4.statement)
evaluate:531, ActivityTestRule$ActivityStatement (androidx.test.rule)
evaluate:20, RunRules (org.junit.rules)
runLeaf:325, ParentRunner (org.junit.runners)
runChild:78, BlockJUnit4ClassRunner (org.junit.runners)
runChild:57, BlockJUnit4ClassRunner (org.junit.runners)
run:290, ParentRunner$3 (org.junit.runners)
schedule:71, ParentRunner$1 (org.junit.runners)
runChildren:288, ParentRunner (org.junit.runners)
access$000:58, ParentRunner (org.junit.runners)
evaluate:268, ParentRunner$2 (org.junit.runners)
run:363, ParentRunner (org.junit.runners)
run:104, AndroidJUnit4 (androidx.test.ext.junit.runners)
runChild:128, Suite (org.junit.runners)
runChild:27, Suite (org.junit.runners)
run:290, ParentRunner$3 (org.junit.runners)
schedule:71, ParentRunner$1 (org.junit.runners)
runChildren:288, ParentRunner (org.junit.runners)
access$000:58, ParentRunner (org.junit.runners)
evaluate:268, ParentRunner$2 (org.junit.runners)
run:363, ParentRunner (org.junit.runners)
run:137, JUnitCore (org.junit.runner)
run:115, JUnitCore (org.junit.runner)
execute:56, TestExecutor (androidx.test.internal.runner)
onStart:388, AndroidJUnitRunner (androidx.test.runner)
run:2075, Instrumentation$InstrumentationThread (android.app)

1 Ответ

0 голосов
/ 06 июня 2019

Вы должны CountingIdlingResource, Вызов приращения () в onPreExecute () AsyncTask и уменьшение () в onPostExecute ()

https://developer.android.com/reference/androidx/test/espresso/idling/CountingIdlingResource.html

...