Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
603 views
in Technique[技术] by (71.8m points)

testing - How to read a file from src/instrumentTest/resources directory in Android?

I have an Android application using the new standard gradle layout:

  src/main/java
  src/main/resources
  src/instrumentTest/java
  src/instrumentTest/resources

I have a unit test in src/instrumentTest/java/com/example/MyUnitTest.java that reads a file located in src/instrumentTest/resources/testfile.json

  • First question: Is it the right place for placing the testing files?
  • Second question: How can I read that file in a String?

I have tried these two ways for reading the file in the unit test with no success (it cannot find the file):

String myJson = new Scanner(new File("testfile.json"),"UTF-8").useDelimiter("\A").next();

String myJson = new Scanner(new File("resources/testfile.json"),"UTF-8").useDelimiter("\A").next();

Cheers!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can use the assets folder of the build type your are testing. If you are testing the debug type (which is the default one):

src/debug/res/assets

And then you access those files with

InputStream raw = context.getAssets().open("filename.ext");
String myJson = new Scanner(raw).useDelimiter("\A").next();

The trick of using the debug build type prevent your testing resources to be packed in the final apk.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...