2014-09-23 2 views
29

Ниже приведено одно из моих тестовых примеров эспрессо.Espresso - Как проверить, запускается ли действие после выполнения определенного действия?

public void testLoginAttempt() { 
     Espresso.onView(ViewMatchers.withId(R.id.username)).perform(ViewActions.clearText()).perform(ViewActions.typeText("[email protected]")); 
     Espresso.onView(ViewMatchers.withId(R.id.username)).perform(ViewActions.clearText()).perform(ViewActions.typeText("invalidpassword")); 

     Espresso.onView(ViewMatchers.withId(R.id.login_button)).perform(ViewActions.click()); 
     // AFTER CLICKING THE BUTTON, A NEW ACTIVITY WILL POP UP. 
     // Clicking launches a new activity that shows the text entered above. You don't need to do 
     // anything special to handle the activity transitions. Espresso takes care of waiting for the 
     // new activity to be resumed and its view hierarchy to be laid out. 
     Espresso.onView(ViewMatchers.withId(R.id.action_logout)) 
       .check(ViewAssertions.matches(not(ViewMatchers.isDisplayed()))); 

    } 

В настоящее время, что я сделал, чтобы проверить, если посмотреть на новый вид деятельности (R.id.action_logout) является visibible или нет. Если видишь, я буду считать, что активность открыта успешно. Но он не работает так, как я ожидал. Есть ли лучший способ проверить, успешно ли запущена новая активность, а не проверять вид в этом действии? Thanks

+0

Почему вы не импортировать ViewMatchers?'import static android.support.test.espresso.matcher.ViewMatchers. *' – Roel

+0

@ user2062024 Можете ли вы опубликовать рабочий код? –

+0

Новый Espresso автоматически ждет Asyntask. – WenChao

ответ

6

Проблема в том, что ваше приложение выполняет сетевую операцию после нажатия кнопки входа в систему. Espresso не обрабатывает (ждать) сетевых вызовов, чтобы завершить по умолчанию. Вы должны реализовать свой собственный IdlingResource, который заблокирует эспрессо от продолжения тестов до тех пор, пока IdlingResource не вернется в состояние ожидания, а это означает, что сетевой запрос завершен. Посмотрите на странице Эспрессо образцов - https://google.github.io/android-testing-support-library/samples/index.html

+0

Обновлено устаревшая ссылка – denys

7

Try с

intended(hasComponent(new ComponentName(getTargetContext(), ExpectedActivity.class))); 

Посмотрите на response from @riwnodennyk

+1

Зачем нужно «новое имя компонента»? –

35

Вы можете использовать:

intended(hasComponent(YourExpectedActivity.class.getName())); 

Требует этот Gradle запись:

androidTestCompile ("com.android.support.test.espresso:espresso-intents:$espressoVersion") 

импорта для intended() и hasComponent()

import static android.support.test.espresso.intent.Intents.intended; 
import static android.support.test.espresso.intent.matcher.IntentMatchers.hasComponent; 
-3
@RunWith(RobolectricTestRunner.class) 
public class WelcomeActivityTest { 

    @Test 
    public void clickingLogin_shouldStartLoginActivity() { 
     WelcomeActivity activity = Robolectric.setupActivity(WelcomeActivity.class); 
     activity.findViewById(R.id.login).performClick(); 

     Intent expectedIntent = new Intent(activity, LoginActivity.class); 
     assertThat(shadowOf(activity).getNextStartedActivity()).isEqualTo(expectedIntent); 
    } 
} 
+1

Вопрос о Эспрессо, а не Робоэлектрике. – Allison

3

Вы можете сделать это следующим образом:

@Test 
public void testLoginAttempt() { 
    Espresso.onView(ViewMatchers.withId(R.id.username)).perform(ViewActions.clearText()).perform(ViewActions.typeText("[email protected]")); 
    Espresso.onView(ViewMatchers.withId(R.id.username)).perform(ViewActions.clearText()).perform(ViewActions.typeText("invalidpassword")); 

    Intents.init(); 
    Espresso.onView(ViewMatchers.withId(R.id.login_button)).perform(ViewActions.click()); 
    Intents.release(); 
} 

java.lang.NullPointerException отбрасывается, если Intents.init() не называется.

0

Убедитесь, что Expresso намерение библиотеки в Gradle зависимостей

androidTestImplementation "com.android.support.test.espresso:espresso-intents:3.0.1" 

Затем импортировать эти два в тестовом файле

import android.support.test.espresso.intent.Intents.intended 
import android.support.test.espresso.intent.matcher.IntentMatchers.hasComponent 

Затем добавьте IntentsTestRule в тестовом классе

@Rule 
@JvmField 
val mainActivityRule = IntentsTestRule(MainActivity::class.java) 

Наконец, проверка активности запустила цель

@Test 
fun launchActivityTest() { 
    onView(ViewMatchers.withId(R.id.nav_wonderful_activity)) 
      .perform(click()) 

    intended(hasComponent(WonderfulActivity::class.java!!.getName())) 
} 
3

Try:

intended(hasComponent(YourActivity.class.getName()));

Кроме того, имейте в виду

java.lang.NullPointerException отбрасывается, если Intents.init() не вызывается до intended()

Смежные вопросы