Android junit 테스트 케이스에서 테스트 프로젝트의 컨텍스트 가져 오기
누구든지 Android junit 테스트 케이스에서 테스트 프로젝트 의 컨텍스트를 얻는 방법을 알고 있습니까 (AndroidTestCase 확장).
참고 : 테스트는 계측 테스트가 아닙니다.
참고 2 : 테스트되는 실제 애플리케이션의 컨텍스트가 아니라 테스트 프로젝트의 컨텍스트가 필요합니다.
테스트 프로젝트의 자산에서 일부 파일을로드하려면 이것이 필요합니다.
Android 테스트 지원 라이브러리 (현재 androidx.test:runner:1.1.1
)에 새로운 접근 방식이 있습니다 . Kotlin 업데이트 예 :
class ExampleInstrumentedTest {
lateinit var instrumentationContext: Context
@Before
fun setup() {
instrumentationContext = InstrumentationRegistry.getInstrumentation().context
}
@Test
fun someTest() {
TODO()
}
}
앱 컨텍스트도 실행하려면 다음을 수행하십시오.
InstrumentationRegistry.getInstrumentation().targetContext
전체 실행 예제 : https://github.com/fada21/AndroidTestContextExample
여기를보세요 : getTargetContext ()와 getContext (IntrumentationRegistry에서)의 차이점은 무엇입니까?
몇 가지 연구 후에 유일한 해결책은 yorkw가 이미 지적한 것입니다. InstrumentationTestCase를 확장 한 다음 getInstrumentation (). getContext ()를 사용하여 테스트 애플리케이션의 컨텍스트에 액세스 할 수 있습니다. 다음은 위의 제안을 사용한 간단한 코드 스 니펫입니다.
public class PrintoutPullParserTest extends InstrumentationTestCase {
public void testParsing() throws Exception {
PrintoutPullParser parser = new PrintoutPullParser();
parser.parse(getInstrumentation().getContext().getResources().getXml(R.xml.printer_configuration));
}
}
당신이 읽을 수있는 것처럼 AndroidTestCase 소스 코드 의 getTestContext()
방법은 숨겨져 있습니다.
/**
* @hide
*/
public Context getTestContext() {
return mTestContext;
}
@hide
리플렉션을 사용 하여 주석을 무시할 수 있습니다 .
다음 방법을 추가하십시오 AndroidTestCase
.
/**
* @return The {@link Context} of the test project.
*/
private Context getTestContext()
{
try
{
Method getTestContext = ServiceTestCase.class.getMethod("getTestContext");
return (Context) getTestContext.invoke(this);
}
catch (final Exception exception)
{
exception.printStackTrace();
return null;
}
}
그런 다음 getTestContext()
원하는 시간에 전화 하십시오. :)
업데이트 : AndroidTestCase
이 클래스는 API 레벨 24에서 더 이상 사용되지 않습니다 InstrumentationRegistry
. 대신 사용하십시오 . Android 테스트 지원 라이브러리를 사용하여 새 테스트를 작성해야합니다. 공지 사항 링크
You should extend from AndroidTestCase instead of TestCase.
AndroidTestCase Class Overview
Extend this if you need to access Resources or other things that depend on Activity Context.
AndroidTestCase - Android Developers
If you want to get the context with Kotlin and Mockito, you can do it in the following way:
val context = mock(Context::class.java)
I Hope its help you
This is to correct way to get the Context. Other methods are already deprecated
import androidx.test.platform.app.InstrumentationRegistry
InstrumentationRegistry.getInstrumentation().context
If you need just access to resources of your project you can use getActivity() method of ActivityInstrumentationTestCase2 class:
//...
private YourActivityClass mActivity;
@Override
protected void setUp() throws Exception {
//...
mActivity = getActivity();
}
//...
public void testAccessToResources() {
String[] valueList;
valueList =
mActivity.getResources().getStringArray(
com.yourporject.R.array.test_choices);
}
The other answers are outdated. Right now every time that you extend AndroidTestCase, there is mContext Context object that you can use.
You can use Robolectric
for Android unit testing on the JVM.
Robolectric
is a framework that allows you to write unit tests and run them on a desktop JVM while still using Android API.
Robolectric
provides a JVM compliant version of the android.jar file. Robolectric handles inflation of views, resource loading, and lots of other stuff that’s implemented in native C code on Android devices.
dependencies {
...
// Robolectric
testCompile "org.robolectric:robolectric:3.3.2"
}
- Your tests should be stored in the
src/test
directory. - The class containing your Robolectric test must be annotate with the
@RunWith(RobolectricTestRunner.class
test runner. - It must also use the @Config() to point to your BuildConfig.class class.
For Example
@RunWith(RobolectricTestRunner.class)
@Config(constants = BuildConfig.class)
public class WelcomeActivityTest
{
private WelcomeActivity activity;
@Before
public void setUp() throws Exception
{
activity = Robolectric.buildActivity( WelcomeActivity.class )
.create()
.resume()
.get();
}
@Test
public void shouldNotBeNull() throws Exception
{
assertNotNull( activity );
}
}
Read more here
import androidx.test.core.app.ApplicationProvider;
private Context context = ApplicationProvider.getApplicationContext();
참고URL : https://stackoverflow.com/questions/8605611/get-context-of-test-project-in-android-junit-test-case
'Programing' 카테고리의 다른 글
네이티브 애플리케이션 개발을위한 Phonegap 사용 (0) | 2020.08.23 |
---|---|
pfx 형식을 p12로 변환 (0) | 2020.08.23 |
CSS 속성 선택기가 href가 작동하지 않습니다. (0) | 2020.08.23 |
객체 속성이 ko.observable인지 확인합니다. (0) | 2020.08.23 |
Jade 대신 Express에서 HTML 사용 (0) | 2020.08.23 |