Android 에서 unit test할 때, Context 값을 가져오는 방법 : ApplicationProvider.getApplicationContext()

 

주의사항 : 위의함수는 @Before method 안에서 호출해야 한다. 

               @BeforeClass 안에서 하게 되면 에러가 발생한다.

 

에러 메시지 : java.lang.IllegalStateException: No instrumentation registered! Must run under a registering instrumentation.

 

Reference : developer.android.com/training/testing/unit-testing/local-unit-tests#java

 

로컬 단위 테스트 빌드  |  Android 개발자  |  Android Developers

테스트를 더 빠르게 실행해야 하고 실제 기기에서 테스트를 실행함으로써 얻는 충실도와 신뢰도가 필요하지 않은 경우 로컬 단위 테스트를 사용하여 앱 로직을 평가할 수 있습니다. 이 접근 방�

developer.android.com

 

--------------------------------------------------------

문서를 제대로 안 읽었더니 해야할게 더 있네요.. (구글링) 

아래와 같이 RobolectricTestRunner 도 추가를 해야 하네요.. 

흠.. 문서엔 안 적혀있는데, stack overflow에선 넣어야 한다고 나오네요 ㅡㅡ

 

@Config(manifest = Config.NONE)
@RunWith(RobolectricTestRunner.class)

public class XXXunitest{

 

}

 

근데 저걸 넣을려면, 

gradle 설정에 아래와 같이 dependency 설정도 해줘야 합니다. 

 

testImplementation "org.robolectric:robolectric:4.2.1"

 

간단하게 기술하렸는데..

길어졌네요 ㅡㅡ;