Espresso Web

Espresso-Web은 Android WebView UI 구성요소를 사용하기 위한 진입점입니다. Espresso-Web은 인기 WebDriver API의 Atom을 재사용하여 WebView의 동작을 검사하고 제어합니다.

Espresso-Web 사용 시기

하이브리드 앱, 특히 Espresso-Web의 통합을 테스트하려면 Espresso-Web을 WebView를 포함하는 앱의 네이티브 UI 구성요소 UI 구성요소 Espresso-Web API를 다른 웹 서버와 함께 WebView 객체 내의 웹 요소와 완전히 상호작용하는 Espresso API

WebView 자체만 테스트해야 하고 WebView와 앱의 네이티브 구성요소 간의 상호작용을 알아보려면 WebDriver와 같은 프레임워크를 사용하여 일반 웹 테스트 작성 웹 테스트 프레임워크를 사용하면 Android 기기 또는 Java Virtual Machine을 사용해야 하므로 더 빠르고 안정적으로 실행할 수 있습니다 그렇긴 하지만 Espresso-Web을 사용하면 맞춤 WebDriver Atom을 사용하므로 특히 는 독립형 웹 앱과 Android UI가 포함된 앱

작동 방식

Espresso의 onData()와 유사 메서드에서 WebView 상호작용은 여러 개의 Atom으로 구성됩니다. WebView 상호작용은 Java 프로그래밍 언어와 JavaScript 브리지를 사용하여 작업을 수행할 수 있습니다. 새로운 캡션 모델을 자바스크립트 환경에서 데이터를 노출함으로써 Espresso는 Java 기반 측면에서 격리된 사본임을 확인합니다. 즉, Web.WebInteraction 드림 객체가 완전히 지원되므로 요청할 수 있습니다

WebDriver Atom이란?

WebDriver 프레임워크는 Atom을 사용하여 웹 요소를 찾고 조작합니다. 설정할 수 있습니다. Atom은 WebDriver에서 브라우저 조작을 허용하는 데 사용됩니다. Atom은 개념적으로 ViewAction: 독립 실행형 UI에서 작업을 실행하는 광고 단위입니다. Atom을 노출하려면 findElement()getElement()와 같은 정의된 메서드를 사용하여 어떤 일이 벌어지는지 알 수 있습니다. 하지만 WebDriver를 사용하는 경우에는 Atom을 적절히 오케스트레이션해야 하기 때문에 매우 상세합니다.

Espresso 내에서 Web 클래스 및 Web.WebInteraction 이 상용구를 래핑하여 Espresso에서 WebView와 상호작용하는 것과 같은 느낌을 줍니다. 객체입니다. 따라서 WebView의 컨텍스트에서 Atom은 다음과 같이 사용됩니다. 기존 Espresso ViewMatchersViewActions를 대체합니다.

그러면 다음과 같이 API가 매우 단순해집니다.

Kotlin

onWebView()
    .withElement(Atom)
    .perform(Atom)
    .check(WebAssertion)

자바

onWebView()
    .withElement(Atom)
    .perform(Atom)
    .check(WebAssertion);

자세히 알아보려면 Atom에 관한 Selenium 문서를 읽어보세요.

WebView 구현

작업하려면 다음 섹션에 표시된 안내를 따르세요. WebView

패키지

Espresso-Web을 프로젝트에 포함하려면 다음 단계를 완료하세요.

  1. 앱의 build.gradle 파일을 엽니다. 이것은 일반적으로 최상위 build.gradle 파일을 지원하지만 app/build.gradle입니다.
  2. 종속 항목 내부에 다음 행을 추가합니다.

    Groovy

        androidTestImplementation 'androidx.test.espresso:espresso-web:3.6.1'
        

    Kotlin

        androidTestImplementation('androidx.test.espresso:espresso-web:3.6.1')
        
  3. Espresso-Web은 Espresso 2.2 이상 및 버전 0.3 이상에 해당하므로 최신 버전을 업데이트해야 합니다. 다음 행도 확인할 수 있습니다.

    Groovy

        androidTestImplementation 'androidx.test:runner:1.6.1'
        androidTestImplementation 'androidx.test:rules:1.6.1'
        androidTestImplementation 'androidx.test.espresso:espresso-core:3.6.1'
        

    Kotlin

        androidTestImplementation('androidx.test:runner:1.6.1')
        androidTestImplementation('androidx.test:rules:1.6.1')
        androidTestImplementation('androidx.test.espresso:espresso-core:3.6.1')
        

일반적인 API 사용

onWebView() 메서드는 Android에서 WebView로 작업할 때 기본 진입점입니다. 있습니다. 이 메서드를 사용하여 다음과 같은 Espresso-Web 테스트를 실행합니다. 있습니다.

Kotlin

onWebView()
    .withElement(findElement(Locator.ID, "link_2")) // similar to onView(withId(...))
    .perform(webClick()) // Similar to perform(click())

    // Similar to check(matches(...))
    .check(webMatches(getCurrentUrl(), containsString("navigation_2.html")))

자바

onWebView()
    .withElement(findElement(Locator.ID, "link_2")) // similar to onView(withId(...))
    .perform(webClick()) // Similar to perform(click())

    // Similar to check(matches(...))
    .check(webMatches(getCurrentUrl(), containsString("navigation_2.html")));

이 예에서 Espresso-Web은 ID가 "link_2"인 DOM 요소를 찾습니다. 클릭합니다. 그런 다음 도구는 WebView가 GET 요청을 보내는지 확인합니다. "navigation_2.html" 문자열을 포함합니다.

자바스크립트 지원

테스트를 실행할 때 시스템은 있습니다. 따라서 JavaScript 평가를 지원하기 위해 테스트 중인 WebView는 JavaScript가 사용 설정되어 있어야 합니다.

다음을 호출하여 자바스크립트를 강제로 사용 설정할 수 있습니다. forceJavascriptEnabled() 드림 액티비티에서 액션으로 테스트를 참조하세요 다음 코드 스니펫을 사용하세요.

@RunWith(AndroidJUnit4::class)
class MyTestSuite {
    @get:Rule val activityScenarioRule =
        activityScenarioRule<MyWebViewActivity>()

    @Test fun testWebViewInteraction() {
        onWebView().forceJavascriptEnabled()
    }
}

일반적인 웹 상호작용

Web.WebInteraction 객체와의 일반적인 상호작용에는 다음이 포함됩니다.

  • withElement() WebView 내에서 DOM 요소를 참조합니다.

    예:

    Kotlin

    onWebView().withElement(findElement(Locator.ID, "teacher"))
    

    자바

    onWebView().withElement(findElement(Locator.ID, "teacher"));
    
  • <ph type="x-smartling-placeholder"></ph> withContextualElement()는 범위가 지정된 DOM 요소를 참조합니다. 다른 DOM 요소와 비교하여 WebView 내에서 이루어집니다. 먼저 withElement()하여 참조를 설정 Web.WebInteraction 객체 (DOM 요소)

    예:

    Kotlin

    .withElement(findElement(Locator.ID, "teacher"))
        .withContextualElement(findElement(Locator.ID, "person_name"))
    

    자바

    .withElement(findElement(Locator.ID, "teacher"))
        .withContextualElement(findElement(Locator.ID, "person_name"));
    
  • <ph type="x-smartling-placeholder"></ph> check()는 조건을 평가하여 해결되는지 확인합니다. true에게.

    예:

    Kotlin

    onWebView()
        .withElement(findElement(Locator.ID, "teacher"))
        .withContextualElement(findElement(Locator.ID, "person_name"))
        .check(webMatches(getText(), containsString("Socrates")))
    

    자바

    onWebView()
        .withElement(findElement(Locator.ID, "teacher"))
        .withContextualElement(findElement(Locator.ID, "person_name"))
        .check(webMatches(getText(), containsString("Socrates")));
    
  • <ph type="x-smartling-placeholder"></ph> perform()는 WebView 내에서 다음과 같은 작업을 실행합니다. 요소만 클릭하면 됩니다.

    예:

    Kotlin

    onWebView()
        .withElement(findElement(Locator.ID, "teacher"))
        .perform(webClick())
    

    자바

    onWebView()
        .withElement(findElement(Locator.ID, "teacher"))
        .perform(webClick());
    
  • reset() WebView를 초기 상태로 되돌립니다. 이는 사전 정의된 클릭과 같은 작업을 할 때 탐색 변경을 통해 ElementReference 및 WindowReference 객체에 액세스할 수 없습니다.

    참고: 다음과 같은 경우 reset()가 유용하지만 양식 제출과 같은 다중 페이지 워크플로에 대해 어설션하기 일반적으로 테스트의 범위가 제한되고 단일 페이지에 중점을 두어야 합니다.

    예:

    Kotlin

    onWebView()
        .withElement(...)
        .perform(...)
        .reset()
    

    자바

    onWebView()
        .withElement(...)
        .perform(...)
        .reset();
    

다음 예는 WebView에 텍스트를 입력한 후 Submit 버튼을 선택하면 스프레드시트의 다른 요소 내에 동일한 WebView를 사용합니다.

Kotlin

const val MACCHIATO = "Macchiato"

@RunWith(AndroidJUnit4::class)
class MyEspressoWebTestSuite {

    @Test fun typeTextInInput_clickButton_SubmitsForm() {
        // Create an intent that displays a web form.
        val webFormIntent = Intent()
        // ...

        // Lazily launch the Activity with a custom start Intent per test.
        ActivityScenario.launchActivity(webFormIntent)

        // Selects the WebView in your layout. If you have multiple WebView
        // objects, you can also use a matcher to select a given WebView,
        // onWebView(withId(R.id.web_view)).
        onWebView()
            // Find the input element by ID.
            .withElement(findElement(Locator.ID, "text_input"))

            // Clear previous input and enter new text into the input element.
            .perform(clearElement())
            .perform(DriverAtoms.webKeys(MACCHIATO))

            // Find the "Submit" button and simulate a click using JavaScript.
            .withElement(findElement(Locator.ID, "submitBtn"))
            .perform(webClick())

            // Find the response element by ID, and verify that it contains the
            // entered text.
            .withElement(findElement(Locator.ID, "response"))
            .check(webMatches(getText(), containsString(MACCHIATO)))
    }
}

Java

public static final String MACCHIATO = "Macchiato";

@Test
public void typeTextInInput_clickButton_SubmitsForm() {
    // Create an intent that displays a web form.
    Intent webFormIntent = new Intent();
    // ...

    // Lazily launch the Activity with a custom start Intent per test.
    ActivityScenario.launchActivity(webFormIntent);

    // Selects the WebView in your layout. If you have multiple WebView objects,
    // you can also use a matcher to select a given WebView,
    // onWebView(withId(R.id.web_view)).
    onWebView()
        // Find the input element by ID.
        .withElement(findElement(Locator.ID, "text_input"))

        // Clear previous input and enter new text into the input element.
        .perform(clearElement())
        .perform(DriverAtoms.webKeys(MACCHIATO))

        // Find the "Submit" button and simulate a click using JavaScript.
        .withElement(findElement(Locator.ID, "submitBtn"))
        .perform(webClick())

        // Find the response element by ID, and verify that it contains the
        // entered text.
        .withElement(findElement(Locator.ID, "response"))
        .check(webMatches(getText(), containsString(MACCHIATO)));
}

추가 리소스

Android 테스트에서 Espresso-Web을 사용하는 방법에 관한 자세한 내용은 확인할 수 있습니다

샘플

  • WebBasicSample: Espresso-Web을 사용하여 WebView 객체와 상호작용합니다.