访问android测试项目中的资源

Zit*_*rax 19 eclipse android unit-testing

我已经设置了一个运行junit测试的android测试项目.它正在使用两个eclipse项目"Application"和"ApplicationTest",我的测试在"ApplicationTest"项目中.在我的一个测试中,我需要访问一个文件,如果我把文件放在SD卡上并指向一个File对象,这个工作正常.但是我想将该文件作为资源访问,但这似乎不起作用.这就是我做的:

  • 保存文件 ApplicationTest/res/raw/myfile.xml
  • 试图使用它: InputStream is = getContext().getResources().openRawResource(R.raw.myfile);

但这给了我这个例外:

android.content.res.Resources$NotFoundException: File Hello World, HelloAndroidActivity! from drawable resource ID #0x7f040000
at android.content.res.Resources.openRawResource(Resources.java:823)
at android.content.res.Resources.openRawResource(Resources.java:799)
at com.quizzer.test.QuestionHandlerTests.testImportQuestions(Tests.java:182)
at java.lang.reflect.Method.invokeNative(Native Method)
at android.test.AndroidTestRunner.runTest(AndroidTestRunner.java:169)
at android.test.AndroidTestRunner.runTest(AndroidTestRunner.java:154)
at android.test.InstrumentationTestRunner.onStart(InstrumentationTestRunner.java:529)
at android.app.Instrumentation$InstrumentationThread.run(Instrumentation.java:1448)
Caused by: java.io.FileNotFoundException: Hello World, HelloAndroidActivity!
at android.content.res.AssetManager.openNonAssetNative(Native Method)
at android.content.res.AssetManager.openNonAsset(AssetManager.java:406)
at android.content.res.Resources.openRawResource(Resources.java:820)
... 14 more

我的测试类扩展了AndroidTestCase,这就是上下文的来源.

更新:

所以问题似乎是在编译期间使用了测试项目中的资源,但是在运行时使用了主项目中的资源.我还不确定如何解决这个问题.因此,目前只有在测试项目和主项目中放置相同的原始资源时才有效,这当然是非常愚蠢的.

ple*_*vlk 24

我建议延长ActivityTestCase而不是AndroidTestCase.您可以通过访问测试项目资源

getInstrumentation().getContext().getResources().openRawResource(R.raw.your_res).

虚拟测试用例示例:

public class Test extends ActivityTestCase {

   public void testFoo() {  

      // .. test project environment
      Context testContext = getInstrumentation().getContext();
      Resources testRes = testContext.getResources();
      InputStream ts = testRes.openRawResource(R.raw.your_res);

      assertNotNull(testRes);
   }    
}
Run Code Online (Sandbox Code Playgroud)

然后在测试方法中使用getInstrumentation().getTargetContext()getContext()AndroidTestCase扩展中使用的任何位置.

  • getTargetContext()做到了!指出这一点。 (2认同)