Hun's Blog

[Android] Android Test 3 - UI Test (Espresso) 본문

Android

[Android] Android Test 3 - UI Test (Espresso)

jhk-im 2020. 3. 22. 08:59

Espresso 


안드로이드 스튜디오에 포함되어있다.
Espresso SDK를 활용하여 UI 테스트를 간단하게 도와주는 기능을 제공한다.

사용법
1. app - build.gradle - dependencies

1
2
3
4
5
// Espresso
androidTestImplementation 'com.android.support.test:runner:1.0.2'
androidTestImplementation 'com.android.support.test:rules:1.0.2'
androidTestImplementation 'com.android.support:support-annotations:28.0.0'
 

-> 코드를 작성할 때 편리하게 사용. 이것을 활용해 프로그램의 결함을 찾아 낼 수 있음.
ex ) JUnit 의 @Test 주석

*Annotation
@Before : @Test 시작하기 전 사전에 진행해야 할 정의
@After : 모든 테스트가 종료되면 호출. 메모리에서 resource를 release 할 수 있다.
@Test : @Before가 완료되면 실제 코드 테스트를 진행
@Rule : 해당 Test 클래스에서 사용하게 될 Rule에 대해 정의
....

2. app - build.gradle - defaultConfig
// EspressotestInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"

테스트 시나리오
*JUnit 예제를 그대로 사용함
1. 커피 수량증가 버튼클릭
2. 커피 수량이 1이되면 MOVE 버튼을 클릭한다.
3. SecondActivity로 이동하고 커피수량을 전달받아 TextView에 셋팅한다.

버튼 추가

1
2
3
4
5
<Button
    android:id="@+id/button_move"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="move" />
 


MainActivity

1
findViewById(R.id.button_move).setOnClickListener(this);
 


MainActivity_onClick메서드

1
2
3
4
5
case R.id.button_move:
    Intent intent = new Intent(getApplicationContext(),SecondActivity.class);
    intent.putExtra("count",mCoffeeCount.getText().toString());
    intent.putExtra("total",Integer.parseInt(mCoffeeCount.getText().toString())*DEFAULT_COFFEE_PRICE);
    startActivity(intent);
 
http://colorscripter.com/info#e" target="_blank" style="text-decoration:none;color:white">cs


CoffeeOrderEspressoTest 생성

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
@RunWith(AndroidJUnit4.class)
 
public class CoffeeOrderEspressoTest {
    @Rule
    public ActivityTestRule<MainActivity> mActivityRule
            = new ActivityTestRule<MainActivity>(MainActivity.class);
    @Test
    public void testChangeTextToSecondActivity() throws Exception {
        //커피 수량 증가 버튼 클릭
        //COUNT 가 1인지 확인
        //액티비티 이동 버튼 클릭
    }
}
 

 

@Rule -> Esppresso 로 UI Test를 진행 할 액티비티와 연결한다.
onView() -> View 연결 및 동작처리
withText(inputText) -> 연결된 text view 에 표시된 text가 inputText와 같은지 판별
withId()-> R.id.view 에 해당하는 View를 찾는다.
perform -> View의 Action을 처리한다.
click -> 해당 아이템 클릭하는 이벤트
check(matches(input)) -> 뷰의 input에 해당하는 특정 상황의 유효성을 체크한다.


testChangTextToSecondActivity() -> 실행 

 

UnitTest와 마찬가지로 안드로이드 스튜디오에서 메소드 옆에 Run 버튼을 클릭하면 Test 클래스에 정의된 부분을 바탕으로 사용자가 클릭처리를 하지 않고 자동으로 테스트하여 결과를 반환해준다.

 

결과



정리 -
Unit Test의 형식처럼 메소드 단위 , 클래스 단위로 나누어 테스트하는 방식과 함께 해당 로직을 자동으로 안드로이드 기기에 빌드하여 테스트하는 것이 UI Test이고 안드로이드에서 기본적으로 지원하는 라이브러리가 Espresso 이다. 

방식을 간단히 정리해보자면 테스트할 뷰를 가지고있는 액티비티를 연결하고 JUnit과 마찬가지로 @Test 와같은 어노태이션을 활용하여 메소드를 단위로 분류하고 그 안에 Espresso에서 지원하는 메소드를 활용하여 view 연결, view의 동작정의, view  동작 유효성 판단등을 하여 자동으로 UI가 클릭되고 메세지가 입력되는 등의 처리를 한다. JUnit과 마찬가지로 메소드를 실행하면 연결된 안드로이드 기기에서 espresso test 클래스에서 정의한 액티비티와 특정 동작들만을 빠르게 빌드하여 테스트 하고 결과를 반환해준다. 

간단하게 정리하자면 Unit Test에 UI 동작까지 더해져서 확인해 볼 수 있는 TEST라는 느낌을 받았다. 이것또한 직접 프로젝트를 만들면서 필요에 따라 활용해보는 것이 좋을 것 같다. 



참고
https://black-jin0427.tistory.com/111

 

[Android, Espresso] Ui Test using Espresso

안녕하세요. 블랙진입니다. 안드로이드 테스트에 관한 포스팅을 진행하고 있습니다. 아래는 이전 포스팅 내용입니다. UnitTest, UiTest 기본 예제 UnitTest using mockito 이번 시간에는 Ui 테스트를 할 수 있는 e..

black-jin0427.tistory.com