9

I am working on an android app and I have created a new test project for unit tests. Where's recommended to store the test fixtures (like xml files and the like) and what's the proper way to access it ?

hyperboreean
  • 8,123
  • 12
  • 59
  • 94

3 Answers3

2

It depends if you really mean unit test or instrumented tests (like using espresso and stuff)...

Unit tests:

  1. Put your fixtures in src/test/resources (so e.g. src/test/resources/fixture.json)
  2. Access them from your test classes e.g. using:

InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("fixture.json")

Instrumented tests:

  1. Put your fixtures in src/androidTest/assets/ (so e.g. src/androidTest/assets/fixture.json)
  2. Access them from your test classes e.g. using:

InputStream is = InstrumentationRegistry.getContext().getResources().getAssets().open("fixture.json")

Here are some examples of how you can convert InputStream to String.

Here's a pretty good post describing different cases.


P.S. I know this question is 6+ years old... answering for any future searches.

Bartek Lipinski
  • 29,328
  • 10
  • 89
  • 127
1

After some searching I found there is no one proper way to store fixtures in Android (also not so much in java either).

Fixtures are a way to provide easy and consistent data to be passed into test cases. Creating .java classes with static methods that return objects is one way to go.

Example:

public class Pojos {

    public static List<TaskListItem> taskListItems() {
        return Arrays.asList(
                new TaskListItem("one"),
                new TaskListItem("two"),
                new TaskListItem("three")
        );
    }
}
Vedant Agarwala
  • 17,082
  • 4
  • 65
  • 81
0

You can configure Gradle to read resources from a shared folder, you will be able to share code and resources either in unit test or instrumented test by doing the following.

android {
    // ...
    sourceSets {

        final String sharedJavaDir = 'src/sharedTest/java'
        final String sharedResourcesDir = 'src/sharedTest/resources'

        test.java.srcDirs += sharedJavaDir
        test.resources.srcDirs += [sharedResourcesDir]

        androidTest.java.srcDirs += sharedJavaDir
        androidTest.resources.srcDirs += [sharedResourcesDir]

        // ....
    }
    // ...
}

Let's imagine that I setup a shared test resource in

/app/src/sharedTest/resources/test_fixture_file.txt

Kotlin code

In a UnitTest or Instrumented test you can use.

val resource: InputStream? = this.javaClass.getResourceAsStream("/test_fixture_file.txt")
Akhha8
  • 194
  • 9