2016년 6월 22일 수요일

Getting Started with Testing

Getting Started with Testing


test를 작성하고 실행하는 것은 안드로이드 앱 개발 사이틀에서 중요한 부분이다. 잘 작성한 테스트는 개발중에 일찍 버그를 잡을 수 있게 도와줄 수 있고 당신 코드에 자신감을 준다. 안드로이드 스튜디오를사용해서 다양한 물리 또는 가상 안드로이드 장치 상에서 local unit test나 instrumented test를 수행할 수 있다. 그러면 결과를 분석해서 개발환경을 벗어날 필요없이 당신의 코드에 수정작업을 할 수 있다.
Local unit tests 는 로컬 머신에서 실행하는 테스트이다. 이는 안드로이드 프레임워크나 안드로이드 장치에 접근할필요가 없다. local units tests를 작성하는지 배우려면 Building Local Unit Tests 를 보아라.
Instrumented tests 는 안드로이드 장치나 에뮬레이터상에서 실행하는 테스트이다. 테스트는 테스트 중에 앱의 Context 와 같은 Instrumentation information 에 접근한다. Instrumented tests는 unit, user interface(UI), 또는 app component integration testing에 사용될 수 있다. 구체적인 필요에 따라 어떻게 instrumented test를 개발하는지 알고 싶으면 다음의 추가적인 주제를 참조해라. :
이 레슨은 어떻게 안드로이드 스튜디오를 이용해서 테스트를 구축하고 실행시키는지 알려준다. 만약 안드로이드 스튜디오를 사용하고 있지 않는다면 run your tests from the command-line 를 사용할 수 있다.

Configure Your Project for Local Unit Tests


안드로이드 스튜디오 프로젝트에서 명확한 소스 디렉토리(src/test/java) 안에 local unit test를 위한 소스 파일들을 저장해야 한다. 이는 당신의 unit tests를 하나의 소스 집합으로 그룹핑함으로써 프로젝트 조직을 새선한다.
생산 코드와 함께 specific flavor or build type 을 위한 local unit tests를 생성할 수 있다. 당신의 unit test를 당신의 생산 소스 트리에 대응하는 test source tree 위치에 유지해라. 다음과 같이:
Path to Production ClassPath to Local Unit Test Class
src/main/java/Foo.javasrc/test/java/FooTest.java
src/debug/java/Foo.javasrc/testDebug/java/FooTest.java
src/myFlavor/java/Foo.javasrc/testMyFlavor/java/FooTest.java
JUnit 4 framework가 제공하는 표준 API들을 사용하는 당신의 프로젝트를 위해 테스팅 의존서을 설정할 필요가 있다. 테스트가 안드로이드 의존성과 상호작용할 필요가 있다면 Mockito 를 포함하여 당신의 local unit test를 단순화시켜라ㅏ. local unit tests에서 mock object를 사용하는 법은 Mocking Android dependencies 를 보아라.
당신 앱의 top-level build.gradle In에 의존성에 대해 이들 라이브러리를 명세할 필요가 있다. :
dependencies {
    // Required -- JUnit 4 framework
    testCompile 'junit:junit:4.12'
    // Optional -- Mockito framework
    testCompile 'org.mockito:mockito-core:1.10.19'
}

Configure Your Project for Instrumented Tests

안드로이드 스튜디오 프로젝트에서 특정 디렉토리(src/androidTest/java)에 당신의 instrumented tests를 위한 소스코드를 위치시켜야 한다.
 Android Testing Support Library Setup 를 다운르도 해라. 이는 당신의 앱을 위한 instrumented 테스트코드를 빠르게 구축하고 실행할 수 있도록 도와준다. Testing Support Library 는 JUnit4 test runner(AndroidJUnitRunner ) 와 기능적인 UI test(Espresso and UI Automator)를 위한 API들을 지원한다.
당신의 프로젝트가 Testing Support Library가 제공하는 test runner와 API 룰들을 사용할 수 있도록 Android testing dependencies 설정할 필요가 있다. 당신의 테스트 개발을 간단하게 하기 위해,우리는  Hamcrest라이브러리를 포함할 것을 추천한다. 이는 Harcrest matcher API들을 이용하여 좀더 유연한 assertions들을 생성할 수 있게 해준다.
당신앱의 top-level build.gradle 파일에, 의존성에 대한 이들 파일들을 명세할 필요가 있다.
dependencies {
    androidTestCompile 'com.android.support:support-annotations:23.0.1'
    androidTestCompile 'com.android.support.test:runner:0.4.1'
    androidTestCompile 'com.android.support.test:rules:0.4.1'
    // Optional -- Hamcrest library
    androidTestCompile 'org.hamcrest:hamcrest-library:1.3'
    // Optional -- UI testing with Espresso
    androidTestCompile 'com.android.support.test.espresso:espresso-core:2.2.1'
    // Optional -- UI testing with UI Automator
    androidTestCompile 'com.android.support.test.uiautomator:uiautomator-v18:2.1.1'
}
To use JUnit 4 test classes, make sure to specify AndroidJUnitRunner as the default test instrumentation runner in your project by including the following setting in your app's module-level build.gradle file:
android {
    defaultConfig {
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
}

Work With Test Artifacts

Android Studio has two types of test artifacts: Android Instrumentation Tests and Unit Tests. Previously, you could work with just one test artifact at a time. Now, both test artifacts are enabled. The advantage of enabling both test artifacts is that any changes you make to the underlying code affect them both. For example, if you rename a class that both test artifacts access, both will know about the class name refactoring.
The figure shows what your project looks like with both test artifacts enabled. Notice the shading of both test artifacts.

Build and Run Your Tests


Android Studio provides all the tools you need to build, run, and analyze your tests within the development environment. You can also run instrumented tests on multiple device configurations, simultaneously, using Cloud Test Lab integration.
Note: While running or debugging instrumented tests, Android Studio does not inject the additional methods required for Instant Run and turns the feature off.

Run Local Unit Tests

To run your local unit tests:
  1. In the Project window, right click on the project and synchronize your project.
  2. In the Project window, navigate to your unit test class or method, then right-click it and select Run .
    • To run all tests in the unit test directory, right-click on the directory and select Run tests .
The Android Plugin for Gradle compiles the local unit test code located in the default directory (src/test/java), builds a test app, and executes it locally using the default test runner class. Android Studio then displays the results in the Run window.

Run Instrumented Tests

To run your instrumented tests:
  • In the Project window, navigate to your instrumented test class or method, then right-click and run it using the Android Test configuration. To run all tests in the instrumented test directory, right-click the directory and select Run tests .
The Android Plugin for Gradle compiles the instrumented test code located in the default directory (src/androidTest/java), builds a test APK and production APK, installs both APKs on the connected device or emulator, and runs the tests. Android Studio then displays the results of the instrumented test execution in the Run window.

Run Instrumented Tests with Cloud Test Lab

Using Cloud Test Lab, you can simultaneously test your app on many popular Android devices, across multiple languages, screen orientations, and versions of the Android platform. These tests run on actual physical devices in remote Google data centers. You can also configure your instrumented tests to take screenshots while Cloud Test Lab runs its tests. You can deploy tests to Cloud Test Lab from the command line, or from Android Studio's integrated testing tools.
Android Studio allows you to connect to your Google Cloud Platform account, configure your tests, deploy them to Cloud Test Lab, and analyze the results all within the development environment. Cloud Test Lab in Android Studio supports the following Android test frameworks: EspressoUI Automator 2.0, or Robotium. Test results provide test logs and include the details of any app failures.
Before you can start using Cloud Test Lab, you need to:
  1. Create a Google Cloud Platform account to use with active billing.
  2. Create a Google Cloud project for your app.
  3. Set up an active billing account and associate it with the project you just created.

Configure a test matrix and run a test

Android Studio provides integrated tools that allow you to configure how you want to deploy your tests to Cloud Test Lab. After you have created a Google Cloud project with active billing, you can create a test configuration and run your tests:
  1. Click Run > Edit Configurations from the main menu.
  2. Click Add New Configuration (+) and select Android Tests.
  3. In the Android Test configuration dialog:
    1. Enter or select the details of your test, such as the test name, module type, test type, and test class.
    2. From the Target drop-down menu under Deployment Target Options, select Cloud Test Lab Device Matrix.
    3. If you are not logged in, click Connect to Google Cloud Platform and allow Android Studio access to your account.
    4. Next to Cloud Project, click the wrench and nut button and select your Google Cloud Platform project from the list.
  4. Create and configure a test matrix:
    1. Next to the Matrix Configuration drop-down list, click Open Dialog ellipses button.
    2. Click Add New Configuration (+).
    3. In the Name field, enter a name for your new configuration.
    4. Select the device(s), Android version(s), locale(s) and screen orientation(s) that you want to test your app with. Cloud Test Lab will test your app against every combination of your selections when generating test results.
    5. Click OK to save your configuration.
  5. Click OK in the Run/Debug Configurations dialog to exit.
  6. Run your tests by clicking Run .

Figure 1. Creating a test configuration for Cloud Test Lab.

Analyzing test results

When Cloud Test Lab completes running your tests, the Run window will open to show the results, as shown in figure 2. You may need to click Show Passed  to see all your executed tests.

Figure 2. Viewing the results of instrumented tests using Cloud Test Lab.
You can also analyze your tests on the web by following the link displayed at the beginning of the test execution log in the Run window, as shown in figure 3.

Figure 3. Click the link to view detailed test results on the web.
To learn more about interpreting web results, see Analyzing Cloud Test Lab Web Results.

댓글 없음: