如何测试执行过程中访问从资产的文件夹中的文件? [英] How to access files from assets folder during tests execution?

查看:297
本文介绍了如何测试执行过程中访问从资产的文件夹中的文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何单元测试执行过程中访问从资产的文件夹中的文件?我的项目是建设使用摇篮,我用Robolectric运行测试。好像摇篮是被承认的资产

How to access files from assets folder during unit tests execution? My project is build using Gradle, I use Robolectric to run tests. It seems like gradle is being recognizing the assets:

这是我如何挣扎来读取文件:

This is how I'm struggling to read the file:

public String readFileFromAssets(String fileName) throws IOException {
    InputStream stream = getClass().getClassLoader().getResourceAsStream("assets/" + fileName);
    Preconditions.checkNotNull(stream, "Stream is null");
    BufferedReader reader = new BufferedReader(new InputStreamReader(stream, "UTF-8"));
    return IOUtils.toString(reader);
}

总是。我尝试了用不同的方法很多不同的方式,即定义文件路径。

But stream is always null. I tried it many different ways, i.e. defined path to a file using different approaches.

非常感谢你提前。

推荐答案

基本上,你必须使用上下文阅读资产。你不能用的ClassLoader ,因为它不是在类路径中加载资产。我不知道你是如何运行Robolectric测试用例。下面是我怎么能在这两个机器人工作室和gralde命令实现。

Basically you have to use Context to read assets. You can not load assets with ClassLoader since it is not in a classpath. I am not sure how you run Robolectric test cases. Here are how I can achieve in both Android studio and gralde command.

我添加单独的应用程序单元测试模块可以在应用程序项目中运行Robolectric测试用例。 通过适当的构建配置和定制 RobolectricTestRunner ,下面的测试情况将成为过去。

I added separate app-unit-test module to run Robolectric test cases in app project. With proper build configuration and custom RobolectricTestRunner, following test case will pass.

@Config
@RunWith(MyRobolectricTestRunner.class)
public class ReadAssetsTest {

    @Test
    public void test_ToReadAssetsFileInAndroidTestContext() throws IOException {

        ShadowApplication application = Robolectric.getShadowApplication();
        Assert.assertNotNull(application);
        InputStream input = application.getAssets().open("b.xml");
        Assert.assertNotNull(input);
    }

}

应用程序单元测试/ build.gradle

app-unit-test/build.gradle

buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:0.14.1'
    }
}

apply plugin: 'java'
evaluationDependsOn(':app')

sourceCompatibility = JavaVersion.VERSION_1_7
targetCompatibility = JavaVersion.VERSION_1_7

repositories {
    maven { url "$System.env.ANDROID_HOME/extras/android/m2repository" } // Fix 'com.android.support:*' package not found issue
    mavenLocal()
    mavenCentral()
    jcenter()
}

dependencies {
    testCompile 'junit:junit:4.8.2'
    testCompile('org.robolectric:robolectric:2.4') {
        exclude module: 'classworlds'
        exclude module: 'commons-logging'
        exclude module: 'httpclient'
        exclude module: 'maven-artifact'
        exclude module: 'maven-artifact-manager'
        exclude module: 'maven-error-diagnostics'
        exclude module: 'maven-model'
        exclude module: 'maven-project'
        exclude module: 'maven-settings'
        exclude module: 'plexus-container-default'
        exclude module: 'plexus-interpolation'
        exclude module: 'plexus-utils'
        exclude module: 'wagon-file'
        exclude module: 'wagon-http-lightweight'
        exclude module: 'wagon-provider-api'
        exclude group: 'com.android.support', module: 'support-v4'
    }
    testCompile('com.squareup:fest-android:1.0.+') {
        exclude group: 'com.android.support', module: 'support-v4'
    }
    testCompile 'org.mockito:mockito-core:1.10.10'
    def appModule = project(':app')
    testCompile(appModule) {
        exclude group: 'com.google.android'
        exclude module: 'dexmaker-mockito'
    }
    testCompile appModule.android.applicationVariants.toList().first().javaCompile.classpath
    testCompile appModule.android.applicationVariants.toList().first().javaCompile.outputs.files
    testCompile 'com.google.android:android:4.1.1.4'
    /* FIXME : prevent Stub! error
        testCompile files(appModule.plugins.findPlugin("com.android.application").getBootClasspath())
        */
    compile project(':app')
}

添加自定义RobolectricTestRunner调整文件路径。 再看资产路径。

Add custom RobolectricTestRunner to adjust file paths. Look at the assets path.

public class MyRobolectricTestRunner extends RobolectricTestRunner {

    private static final String APP_MODULE_NAME = "app";

    /**
     * Creates a runner to run {@code testClass}. Looks in your working directory for your AndroidManifest.xml file
     * and res directory by default. Use the {@link org.robolectric.annotation.Config} annotation to configure.
     *
     * @param testClass the test class to be run
     * @throws org.junit.runners.model.InitializationError if junit says so
     */
    public MyRobolectricTestRunner(Class<?> testClass) throws InitializationError {
        super(testClass);
        System.out.println("testclass="+testClass);
    }

    @Override
    protected AndroidManifest getAppManifest(Config config) {

        String userDir = System.getProperty("user.dir", "./");
        File current = new File(userDir);
        String prefix;
        if (new File(current, APP_MODULE_NAME).exists()) {
            System.out.println("Probably running on AndroidStudio");
            prefix = "./" + APP_MODULE_NAME;
        }
        else if (new File(current.getParentFile(), APP_MODULE_NAME).exists()) {
            System.out.println("Probably running on Console");
            prefix = "../" + APP_MODULE_NAME;
        }
        else {
            throw new IllegalStateException("Could not find app module, app module should be \"app\" directory in the project.");
        }
        System.setProperty("android.manifest", prefix + "/src/main/AndroidManifest.xml");
        System.setProperty("android.resources", prefix + "/src/main/res");
        System.setProperty("android.assets", prefix + "/src/androidTest/assets");

        return super.getAppManifest(config);
    }

}

我跟着这个博客做到这一点。

I followed this blog to do it.

<一个href="http://blog.blundell-apps.com/android-gradle-app-with-robolectric-junit-tests/">http://blog.blundell-apps.com/android-gradle-app-with-robolectric-junit-tests/ <一href="http://blog.blundell-apps.com/how-to-run-robolectric-junit-tests-in-android-studio/">http://blog.blundell-apps.com/how-to-run-robolectric-junit-tests-in-android-studio/

完整的例子codeS是这里

full example codes are here

这篇关于如何测试执行过程中访问从资产的文件夹中的文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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