Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to share resources between unit test and instrumentation test in android?

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?.

like image 460
nebiros Avatar asked Dec 13 '15 21:12

nebiros


People also ask

What is instrumented test in Android?

Instrumented tests run on Android devices, whether physical or emulated. As such, they can take advantage of the Android framework APIs. Instrumented tests therefore provide more fidelity than local tests, though they run much more slowly.

How do I create a test folder in Android?

To add a testing source set for your build variant in Android Studio, follow these steps: In the Project window on the left, click the drop-down menu and select the Project view. Within the appropriate module folder, right-click the src folder and click New > Directory.


Video Answer


1 Answers

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);

like image 158
nebiros Avatar answered Oct 24 '22 19:10

nebiros