Android test raw resource

前端 未结 3 768
别那么骄傲
别那么骄傲 2021-01-01 08:31

I have the following folder structure in Android Studio:

├── androidTest
│   ├── java
│   └── res
│       └── raw
│           └── test_file
└── main
    ├──          


        
相关标签:
3条回答
  • 2021-01-01 09:08

    I had the androidTest resources in the right spot (src/androidTest/res) and I still couldn't access them via <normal.package>.test.R. I spent a lot of time googling trying to figure out what was going on..

    I FINALLY stumbled onto the answer. If you're building a buildType where you specified an applicationIdSuffix, your files are at <applicationId><applicationIdSuffix>.test.R !!!!

    i.e.

    applicationId "com.example.my.app"
    
    buildTypes {
        debug {
            applicationIdSuffix ".debug"
        }
    }
    

    if you have androidTest resources in the right directory, then you can only access them via com.example.my.app.debug.test.R !!!!

    0 讨论(0)
  • 2021-01-01 09:08

    See Android Unit Tests Requiring Context. For instrumentation test use InstrumentationRegistry.getInstrumentation().getTargetContext() (in Kotlin: getInstrumentation().targetContext). Then you can access resources. You won't need to import R file.

    0 讨论(0)
  • 2021-01-01 09:11

    By default your androidTest project will include your app's R class, but androidTest's resources will be generated into a separate file. Make sure you import the R class from your test project:

    import com.your.package.test.R;
    
    [..]
    
    getInstrumentation().getContext().getResources().openRawResource(R.raw.test_file);
    

    You can also directly reference the test project's R class:

    getInstrumentation().getContext().getResources().openRawResource(com.your.package.test.R.raw.test_file);
    
    0 讨论(0)
提交回复
热议问题