How to create file on my computer from Android instrumented tests?

Viewed 395

I want to create text file with output on my laptop(not on Android emulator).

I use this code but it's doesn't work for me:

@Test
fun useAppContext() {
    val appContext = InstrumentationRegistry.getInstrumentation().targetContext

    val str = "OUTPUT"
    val outputStreamWriter =
        OutputStreamWriter(appContext.openFileOutput("output.json", Context.MODE_PRIVATE))
    outputStreamWriter.write(str)
    outputStreamWriter.close()
}

How to write to file on my computer from Android Instrumented tests? (I know that is possible)

3 Answers

How to write to file on my computer from Android Instrumented tests?

An instrumented test is not significantly different from an app, in that it runs in Android (on a device or emulator). An app has no innate ability to write content to a computer; an instrumented test similarly has no innate ability to write content to a computer.

Either:

  • Switch to unit tests, which do run on your computer directly (not inside of Android), or

  • Do something on your own to enable app/test -> computer communications. For example, you might run a Web service on the computer and have the tests talk to it.

I'm tried to write String to file from unit tests and it works!

This is my code:

@Test
fun testName() {
    val str = "OUTPUT"
    val writer = BufferedWriter(FileWriter("output.json"))
    writer.write(str)

    writer.close()
}

I found that the cache directory from the test target context is writable

 val testContext = InstrumentationRegistry.getInstrumentation().context
 var dir = InstrumentationRegistry.getInstrumentation().targetContext.cacheDir
 File(dir, "test.txt").createNewFile()
Related