반응형

Gradle을 통해 Espresso를 설치하는 방법을 알아보겠습니다.
(사실 안드로이드 스튜디오에서 패키지 생성하면 기본 값으로 dependency 가 적용되어 있습니다.)

 

디바이스 테스트 환경 구축

Espresso 는 실제 또는 가상의 디바이스 환경에서 동작하는 테스트입니다. 따라서 테스트 기기에 몇 가지 설정을 해주어야 할 것이 있습니다.

 

옵션 → 개발자 옵션 으로 들어가 다음 3 가지에 대한 설정을 해제 해줍니다.

  • 창 애니메이션 배율(Window animation scale)
  • 전환 애니메이션 배율(Transition animation scale)
  • Animator 길이 배율(Animator duration scale)

 

Espresso Dependencies

Espresso 를 이용해 테스트를 하기 위해서는 프로젝트에 Dependency를 추가 해줘야 합니다.

  1. 앱 수준build.gradle 파일을 엽니다.

  2. 아래와 같이 dependencies 를 추가 해줍니다.

     dependencies {
         // 예제의 버전이 최신 버전이 아닐 수 있습니다.
         androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
         androidTestImplementation 'androidx.test:runner:1.2.0'
         androidTestImplementation 'androidx.test:rules:1.2.0'
     }

 

Instrumentation Runner

위와 같이 앱 수준의 build.gradle 파일의 android.defaultConfig 내에 아래 내용을 추가 해줍니다.

testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"

 

샘플(앱 수준의 biuld.gradle)

apply plugin: 'com.android.application'

android {
    compileSdkVersion 28

    defaultConfig {
        applicationId "com.naver.uitest.sample"
        minSdkVersion 16
        targetSdkVersion 28
        versionCode 1
        versionName "1.0"

        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }
}

dependencies {
      androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
        androidTestImplementation 'androidx.test:runner:1.2.0'
        androidTestImplementation 'androidx.test:rules:1.2.0'
}

 

간단한 테스트

MainActivity에 *"Hello World!"* 를 출력하는 간단한 앱이 있다는 가정 하에 테스트를 작성해보겠습니다.

테스트는 src/androidTest/java/패키지명/ 에 위치합니다.

@RunWith(AndroidJUnit4.class)
@LargeTest
public class HelloWorldEspressoTest {

    @Rule
    public ActivityTestRule<MainActivity> activityRule =
            new ActivityTestRule<>(MainActivity.class);

    @Test
    public void listGoesOverTheFold() {
        onView(withText("Hello World!")).check(matches(isDisplayed()));
    }
}

위 테스트 코드 중 @Runwith , @LargeTest , @Rule 등 어노테이션에 대해서는 추후에 설명하도록 하겠습니다.

 

결과

...
I/TestRunner: run finished: 1 tests, 0 failed, 0 ignored
I/MonitoringInstr: Activities that are still in CREATED to STOPPED: 0
I/MonitoringInstr: waitForActivitiesToComplete() took: 0ms

Tests ran to completion.

 

참고!
테스트 코드가 실행되는 앱은 우리가 구현한 앱과 다른 앱입니다.
예를들어 내가 구현한 앱의 PackageName 이 com.naver.sample 이라면,
테스트 앱의 PackageName 은 com.naver.sample.espresso 가 됩니다.
그렇기 때문에 테스트 하려는 앱의 리소스에 접근하려면 InstrumentationRegistry를 통해 targetContext를 가져와 이를 통해 접근해야 합니다.

 

 

반응형
반응형