How to share resources between unit test and instr

2020-08-14 10:16发布

问题:

I'm following this post, http://blog.danlew.net/2015/11/02/sharing-code-between-unit-tests-and-instrumentation-tests-on-android/, to share code, but how to share an asset?, like a fixture file?, I want to mock an api response, so I have a JSON file to do it, but I try this: https://gist.github.com/nebiros/91a68aaf6995fa635507

In Unit Test, this works:

ClassLoader.getSystemResourceAsStream("some_response.json");

but in Android Intrumentation Tests, it doesn't, where can I put those fixture files?.

回答1:

I found this way, to share fixture files from test to androidTest:

  • Add your fixture files to the resources folder of your test one, here: src/test/resources.
  • Add test resources folder to androidTest, resources.srcDirs += ['src/test/resources'], here's an example:

    android {
        sourceSets {
            String sharedTestJavaDir = 'src/sharedTest/java'
    
            test {
                java.srcDirs += [sharedTestJavaDir]
            }
    
            androidTest {
                java.srcDirs += [sharedTestJavaDir]
                resources.srcDirs += ['src/test/resources']
            }
        }
    }
    
  • Access fixture files from your androidTest env this way: this.getClass().getClassLoader().getResourceAsStream(filename);