Android的工作室单元测试:读取数据(输入)文件 [英] Android Studio unit testing: read data (input) file
问题描述
在一个单元测试,我怎么能读我(台式机)的文件系统,从一个JSON文件中的数据,而不硬编码路径?
In a unit test, how can I read data from a json file on my (desktop) file system, without hardcoding the path?
我想从一个文件,而不是创建静态字符串读取测试输入(我的分析方法)。
I would like to read test input (for my parsing methods) from a file instead of creating static Strings.
的文件是在相同的位置我的单元测试code,但如果需要,我还可以放置在别处在项目中。我使用Android的工作室。
The file is in the same location as my unit testing code, but I can also place it somewhere else in the project if needed. I am using Android Studio.
推荐答案
你应该使用 InstrumentationTestCase
和资产得到的文件。
You should use InstrumentationTestCase
and get the file from assets.
无法从文件系统引用文件,并从POJO JUnit类阅读。
了解更多:
- <一个href="http://stackoverflow.com/questions/3983048/loading-a-text-file-from-androidtestproject">Loading从AndroidTestProject 文本文件
- <一个href="http://stackoverflow.com/questions/9503114/android-test-project-reading-assets-file-to-test-plain-java-object">Android测试项目 - 阅读资源文件来测试普通Java对象
- <一个href="http://stackoverflow.com/questions/9249751/accessing-resources-in-an-android-test-project">Accessing在Android测试项目资源
- Loading a text file from AndroidTestProject
- Android Test Project - Reading assets file to test plain java object
- Accessing resources in an android test project
编辑:
最后,我找到怎样的方式来读取单元测试文件资源。
Finally, I've found the way how to read file resource from the unit test.
-
请确保您使用至少 Android的摇篮插件版本1.1 。请正确设置机器人工作室的链接。
Ensure you're using at least Android Gradle Plugin version 1.1. Follow the link to set up Android Studio correctly.
创建测试
目录。把单元测试类的的Java
目录,放在你的资源文件RES
目录。 Android的工作室应该纪念他们像如下:
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:
创建摇篮
任务的资源复制到classes目录,使他们的的类加载器
可见:
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)
现在你可以使用这个方法来获取文件
的文件资源引用:
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());
}
让我知道,如果你的作品。在我的情况是这样,所以如果你有任何问题随时问:)
Let me know if it works for you. In my case it does, so if you have any problem feel free to ask :)
这篇关于Android的工作室单元测试:读取数据(输入)文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!