Android Studio 单元测试:读取数据(输入)文件 [英] Android Studio unit testing: read data (input) file

查看:56
本文介绍了Android Studio 单元测试:读取数据(输入)文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在单元测试中,如何从我的(桌面)文件系统上的 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.

该文件与我的单元测试代码位于同一位置,但如果需要,我也可以将其放在项目中的其他位置.我正在使用 Android Studio.

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.

推荐答案

取决于 android-gradle-plugin 版本:

1.1.5 及更高版本:

只需将json文件放到src/test/resources/test.json并引用为

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

classLoader.getResource("test.json"). 

不需要修改gradle.

No gradle modification is needed.

2.低于 1.5 的版本:(或者如果由于某种原因上述解决方案不起作用)

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

  1. 确保您至少使用 Android Gradle 插件版本 1.1.按照链接正确设置 Android Studio.

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

创建test 目录.将单元测试类放在 java 目录中,并将您的资源文件放在 res 目录中.Android Studio 应将它们标记为如下所示:

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:

创建 gradle 任务,将资源复制到 classes 目录中,使其对 classloader 可见:

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)

  • 现在你可以使用这个方法来获取文件资源的File引用:

    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());
    }
    

  • 在全班或特定测试方法上通过 Ctrl+Shift+F10 运行单元测试.
  • Run unit test by Ctrl+Shift+F10 on whole class or specyfic test method.
  • 这篇关于Android Studio 单元测试:读取数据(输入)文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆