Android Studio Unit Testing: Read Data (Input) File

Android Studio unit testing: read data (input) file

Depending on android-gradle-plugin version:

1. version 1.5 and higher:

Just put json file to src/test/resources/test.json and reference it as

classLoader.getResource("test.json"). 

No gradle modification is needed.

2. version below 1.5: (or if for some reason above solution doesn't work)

  1. Ensure you're using at least Android Gradle Plugin version 1.1. Follow the link to set up Android Studio correctly.

  2. Create test directory. Put unit test classes in java directory and put your resources file in res directory. Android Studio should mark them like follow:

    Sample Image

  3. Create gradle task to copy resources into classes directory to make them visible for classloader:

    android{
    ...
    }

    task copyResDirectoryToClasses(type: Copy){
    from "${projectDir}/src/test/res"
    into "${buildDir}/intermediates/classes/test/debug/res"
    }

    assembleDebug.dependsOn(copyResDirectoryToClasses)
  4. Now you can use this method to get File reference for the file resource:

    private static File getFileFromPath(Object obj, String fileName) {
    ClassLoader classLoader = obj.getClass().getClassLoader();
    URL resource = classLoader.getResource(fileName);
    return new File(resource.getPath());
    }

    @Test
    public void fileObjectShouldNotBeNull() throws Exception {
    File file = getFileFromPath(this, "res/test.json");
    assertThat(file, notNullValue());
    }
  5. Run unit test by Ctrl+Shift+F10 on whole class or specyfic test method.

How to read a test-only file in Android unit test

At the time when this question was asked this simply wasn't working. Fortunately this has been fixed since.

You have to put your text file under the app/src/test/resources folder as the OP was trying to do. Additionally it has to be in the same package as your test class. So if you have ReadFileTest.java in package com.example.test in app/src/test/java folder, then your test file should be in app/src/test/resources/com/example/test.

test folder structure

Then you can get to your text file like this:

getClass().getResourceAsStream("testFile.txt")

This opens an InputStream for the text file. If you're not sure what do with it, here are some of the many ways you could use it: Read/convert an InputStream to a String

How do I access a text file for JUnit test in Android?

Prefix the file path with /.

Basically, you'd do something like this:

File helloBleprintJson = new File(
getClass().getResource("/helloBlueprint.json").getPath());

Above snippet is taken from here.

How to test file IO in Android unitTest/AndroidTest

I wouldn't test that the file is saved - this is not your system and Android AOSP should have tests for making sure the file actually saves. Read more here

What you want to test is if you are telling Android to save your file. Perhaps like this:

String FILENAME = "hello_file";
String string = "hello world!";
File testFile = new File(context.getFilesDir(), FILENAME);
FileOutputStream fos =new FileOutputStream(file);

public void saveAndClose(String data, FileOutputStream fos) {
fos.write(data.getBytes());
fos.close();
}

Then your test would use Mockito for the FOS and be:

   FileOutputStream mockFos = Mockito.mock(FileOutputStream.class);
String data = "ensure written";

classUnderTest.saveAndClose(data, mockFos);

verify(mockFos).write(data.getBytes());

second test:

   FileOutputStream mockFos = Mockito.mock(FileOutputStream.class);
String data = "ensure closed";

classUnderTest.saveAndClose(data, mockFos);

verify(mockFos).close();

How to provide data files for android unit tests

Option 1: Use InstrumentationTestCase

Suppose you got assets folder in both android project and test project, and you put the XML file in the assets folder. in your test code under test project, this will load xml from the android project assets folder:

getInstrumentation().getTargetContext().getResources().getAssets().open(testFile);

This will load xml from the test project assets folder:

getInstrumentation().getContext().getResources().getAssets().open(testFile);

Option 2: Use ClassLoader

In your test project, if the assets folder is added to project build path (which was automatically done by ADT plugin before version r14), you can load file from res or assets directory (i.e. directories under project build path) without Context:

String file = "assets/sample.xml";
InputStream in = this.getClass().getClassLoader().getResourceAsStream(file);

Android Test Project - Reading assets file to test plain java object

I got this solved by the following :

  • Created the setup as explained here
  • Extended the InstrumentationTestCase instead of TestCase. The InstrumentationTestCase has the method getInstrument() through which I got access to the Instrumentation's(The test app project) Context.


Related Topics



Leave a reply



Submit