ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • Test your app's activites
    Android 공식문서 2020. 10. 27. 08:54
    반응형

    Activities serve as containers for every user interaction within your app, so it's important to test how your app's activities behave during device-level events, such as the following:

    액티비티는 앱 내의 모든 사용자 상호 작용에 대한 컨테이너 역할을 하므로 다음과 같은 기기 수준 이벤트 중에 앱의 액티비티가 어떻게 작동하는지 테스트 하는 것이 중요합니다.
    • Another app, such as the device's phone app, interrupts your app's activity.
    • The system destroys and recreates your activity.
    • The user places your activity in a new windowing environment, such as picture-in-picture (PIP) or multi-window.
    1. 기기의 전화 앱과 같은 다른 앱이 앱의 액티비티를 방해합니다.
    2. 시스템은 액티비티를 파괴하고 재생성합니다.
    3. 사용자는 PIP(picture-in-picture) 또는 multi-window와 같은 새 창 환영에 액티비티를 배치합니다.

    In particular, it's important to ensure that your activity behaves correctly in response to the events described in Understanding the Activity Lifecycle.

    Understanding the Activity Lifecycle에서 설명 된 이벤트에 대한 응답으로 액티비티가 올바르게 작동하는지 확인하는 것이 중요합니다.

    This guide describes how to evaluate your app's ability to maintain data integrity and a good user experience as your app's activities transition through different states in their lifecycles.

    이 가이드에서는 앱의 액티비티가 생명주기의 여러 상태를 통해 전환 될 때 데이터 무결성과 우수한 사용자 경혐을 유지하는 앱의 기능을 평가하는 방법을 설명합니다.

    Drive an activity's state

    One key aspect of testing your app's activities involves placing your app's activities in particular states. To define this "given" part of your tests, use instances of ActivityScenario, part of the AndroidX Test library. By using this class, you can place your activity in states that simulate the device-level events described at the beginning of this page.

    앱의 액티비티 테스트의 한 가지 주요 측면은 앱의 액티비티를 특정 상태에 배치하는 것입니다.
    테스트의 'given" 부분을 정의하려면 AndroidX Text 라이브러이의 일부인 ActivityScenario 인스턴스를 사용하세요.
    이 클래스를 사용하면, 페이지의 시작 부분에 설명 된 장치 수준 이벤트를 시뮬레이션하는 상태에 액티비티를 배치 할 수 있습니다.

    ActivityScenario is a cross-platform API that you can use in local unit tests and on-device integration tests alike. On a real or virtual device, ActivityScenario provides thread safety, synchronizing events between your test's instrumentation thread and the thread that runs your activity under test. The API is also particularly well-suited for evaluating how an activity under test behaves when it's destroyed or created.

    AcitivityScenario는 로컬 단위 테스트와 on-device 통합 테스트에서 모두 사용할 수 있는 크로스 플랫폼 API 입니다.
    실제 또는 가상 장치에서 ActivityScenario는 테스트의 계측 스레드와 테스트중인 액티비티를 실행하는 스레드 간의 이벤트를 동기화하여 스레드 안전성을 제공합니다.
    API는 또한 테스트중인 액티비티가 파괴되거나 생성될 때 어떻게 작동하는지 평가하는 데 특히 적합합니다.

    This section presents the most common use cases associated with this API.

    이 섹션에서는 API와 관련된 가장 일반적인 사용 사례를 보여줍니다.

    Create an activity

    To create the activity under test, add the code shown in the following snippet:

    테스트중인 액티비티를 만들려면 다음 snippet에 표시된 코드를 추가하세요.
    @RunWith(AndroidJUnit4::class)
    class MyTestSuite {
        @Test fun testEvent() {
            val scenario = launchActivity<MyActivity>()
        }
    }

    After creating the activity, ActivityScenario transitions the activity to the RESUMED state. This state indicates that your activity is running and is visible to users. In this state, you're free to interact with your activity's View elements using Espresso UI tests.

    액티비티가 만들어진 후 ActivityScenario는 액티비티를 RESUMED 상태로 전환 시킵니다.
    이 상태는 액티비티가 실행 중이며 사용자에게 표시됨을 나타냅니다.
    이 상태에서는 Espresso UI texts를 사용하여 액티비티의 View 요소와 자유롭게 상호 작용할 수 있습니다.

    Alternatively, you can use ActivityScenarioRule to automatically call ActivityScenario.launch before each test, and ActivityScenario.close at test teardown. The example below shows how to define a rule and get an instance of a scenario from it:

    또는, ActivityScenarioRule을 사용하여 각 테스트 전에 ActivityScenario.launch를 자동으로 호출하고 테스트 해제시 ActivityScenario.close를 호출 할 수 있습니다.
    아래의 예시는 규칙을 정의하고 여기에서 시나리오 인스턴스를 가져 오는 방법을 보여줍니다.
    @RunWith(AndroidJUnit4::class)
    class MyTestSuite {
        @get:Rule var activityScenarioRule = activityScenarioRule<MyActivity>()
    
        @Test fun testEvent() {
            val scenario = activityScenarioRule.scenario
        }
    }

    Drive the activity to a new state

    To drive the activity to a different state, such as CREATED or STARTED, call moveToState(). This action simulates a situation where your activity is stopped or paused, respectively, because it's interrupted by another app or a system action.

    An example usage of moveToState() appears in the following code snippet:

    액티비티를 CREATED 또는 STARTED와 같은 다른 상태로 유도하려면 moveToState()를 호출하십시오.
    이 작업은 다른 앱이나 시스템 작업에 의해 중단되었기 때문에 액티비티가 각각 중지되거나 일시 중지 되는 상황을 시뮬레이션합니다.
    moveToState() 사용 예시는 다음 코드에 나와있습니다.
    @RunWith(AndroidJUnit4::class)
    class MyTestSuite {
        @Test fun testEvent() {
            val scenario = launchActivity<MyActivity>()
            scenario.moveToState(State.CREATED)
        }
    }

    Caution: If you try to transition your activity under test to its current state, ActivityScenario treats this request as a no-op, not an exception.

    테스트중인 액티비티를 현재 상태로 전환하려고하면 ActivityScenario는 이 요청을 예외가 아닌 작업 없음으로 처리합니다.

    Determine the current activity state

    To determine the current state of an activity under test, get the value of the state field within your ActivityScenario object. It's particularly helpful to check the state of an activity under test if the activity redirects to another activity or finishes itself, as demonstrated in the following code snippet:

    테스트중인 액티비티의 현재 상태를 확인하려면 ActivityScenario 개체에서 state 필드의 값을 가져옵니다.
    다음 코드에 설명 된 것처럼 액티비티가 다른 액티비티로 리디렉션되거나 자체적으로 완료되는지 테스트중인 액티비티의 상태를 확인하는 것이 특히 유용합니다.
    @RunWith(AndroidJUnit4::class)
    class MyTestSuite {
        @Test fun testEvent() {
            val scenario = launchActivity<MyActivity>()
            scenario.onActivity { activity ->
              startActivity(Intent(activity, MyOtherActivity::class.java))
            }
    
            val originalActivityState = scenario.state
        }
    }

    Recreate the activity

    If a device is low on resources, the system might destroy an activity, requiring your app to recreate that activity when the user returns to your app. To simulate these conditions, call recreate():

    기기에 리소스가 부족하면 시스템이 액티비티를 파괴하여 사용자가 앱으로 돌아올 때 해당 액티비티를 다시 생성하도록 요구할 수 있습니다.
    이러한 조건을 시뮬레이션하려면 recreate()를 호출하세요.
    @RunWith(AndroidJUnit4::class)
    class MyTestSuite {
        @Test fun testEvent() {
            val scenario = launchActivity<MyActivity>()
            scenario.recreate()
        }
    }

    The ActivityScenario class maintains the activity's saved instance state and any objects annotated using @NonConfigurationInstance. These objects are loaded into the new instance of your activity under test.

    ActivityScenario 클래스는 액티비티의 저장된 인스턴스 상태와 @NonConfigurationInstance를 사용하여 annotation이 추가 된 모든 개체를 유지합니다.
    이러한 개채는 테스트중인 액티비티의 새 인스턴스에 로드됩니다.

    Retrieve activity results

    To get the result code or data associated with a finished activity, get the value of the result field within your ActivityScenario object, as shown in the following code snippet:

    완료된 액티비티와 관련된 결과 코드 또는 데이터를 가져 오려면 다음 코드에 표시된대로 ActivityScenario 개채 내에서 결과 필드의 값을 가져옵니다.
    @RunWith(AndroidJUnit4::class)
    class MyTestSuite {
        @Test fun testResult() {
            val scenario = launchActivity<MyActivity>()
            onView(withId(R.id.finish_button)).perform(click())
    
            // Activity under test is now finished.
    
            val resultCode = scenario.result.resultCode
            val resultData = scenario.result.resultData
        }
    }

    Trigger actions in the activity

    All methods within ActivityScenario are blocking calls, so the API requires you to run them in the instrumentation thread.

    To trigger actions in your activity under test, use Espresso view matchers to interact with elements in your view:

    ActivityScenario 안에 모든 메서드는 호출을 차단하므로 API를 사용하려면 instrumentation thread에서 실행해야합니다.
    테스트중인 액티비티에서 작업을 트리거하려면 Espresso view matchers를 사용하여 뷰의 요소와 상호작용합니다.
    @RunWith(AndroidJUnit4::class)
    class MyTestSuite {
        @Test fun testEvent() {
            val scenario = launchActivity<MyActivity>()
            onView(withId(R.id.refresh)).perform(click())
        }
    }

    If you need to call a method on the activity itself, however, you can do so safely by implementing ActivityAction:

    액티비티 자체에서 메서드를 호출해야하는 경우 ActivityAction을 구현하여 안전하게 수행 할 수 있습니다.
    @RunWith(AndroidJUnit4::class)
    class MyTestSuite {
        @Test fun testEvent() {
            val scenario = launchActivity<MyActivity>()
            scenario.onActivity { activity ->
              activity.handleSwipeToRefresh()
            }
        }
    }
    반응형

    'Android 공식문서' 카테고리의 다른 글

    Handle Activity State Changes  (0) 2020.10.22
    Understand the Activity Lifecycle  (0) 2020.10.16
    Introduction to Activities  (0) 2020.09.22
    Fragment - OverView  (0) 2020.09.11

    댓글

Designed by Tistory.