简体   繁体   English

在 robolectric 测试中使用资产

[英]Using assets in robolectric tests

In my robolectric tests I am trying to read a file.在我的 robolectric 测试中,我试图读取一个文件。 Since this file contains just the test data I have put it in assets of the tests.由于此文件仅包含测试数据,因此我将其放入测试资产中。

The directory structure looks like this.目录结构如下所示。
src/main/assets/prod_data_file
src/test/assets/test_data_file

However when I try to read the file by getShadowApplication().getAssets().open(MY_FILE_PATH) it gives me FileNotFoundException .但是,当我尝试通过getShadowApplication().getAssets().open(MY_FILE_PATH)读取文件时,它给了我FileNotFoundException

Does anybody know how to fix this?有谁知道如何解决这个问题?

Since my tests are just reading these files and returning file data as a String I was able to do that via getClass().getClassLoader().getResourceAsStream(MY_FILE_PATH) and then read file.由于我的测试只是读取这些文件并将文件数据作为String返回,因此我能够通过getClass().getClassLoader().getResourceAsStream(MY_FILE_PATH)然后读取文件。 Dont really need to read to use getShadowApplication().getAssets().open(MY_FILE_PATH) .真的不需要阅读来使用getShadowApplication().getAssets().open(MY_FILE_PATH)

I just moved my test data files to src/test/resources and it worked.我刚刚将我的测试数据文件移动到src/test/resources并且它起作用了。 :) :)

I was able to make it like this:我能够做到这样:

1) Copy (or create) AndroidManifest.xml in test folder 1) 在 test 文件夹中复制(或创建)AndroidManifest.xml

2) Add @Config(emulateSdk = 18, manifest = "src/test/AndroidManifest.xml") for this specific test 2)为此特定测试添加@Config(emulateSdk = 18, manifest = "src/test/AndroidManifest.xml")

I was able to read file.我能够读取文件。 So it means you could play with AndroidManifest class and custom runner (more inspiration herehttps://groups.google.com/forum/#!topic/robolectric/YvbdqRFcdnA )所以这意味着你可以使用AndroidManifest类和自定义运行器(更多灵感在这里https://groups.google.com/forum/#!topic/robolectric/YvbdqRFcdnA

I think it could be also possible to play with build.gradle :我认为也可以使用build.gradle

android {
  sourceSets {
    androidTest.setRoot( 'src/test' )

    androidTest {
      assets.srcDir file( 'src/test/assets' )
    }
  }
}

but I'm not sure since plugin doesn't create any build variant but just tasks.但我不确定,因为插件不创建任何构建变体,而只是任务。

In Android Studio, create test assets folder (right click on the test directory -> New -> Directory -> pick assets from the list).在 Android Studio 中,创建测试资产文件夹(右键单击测试目录 -> 新建 -> 目录 -> 从列表中选择资产)。 Add your file in the test assets folder you just created.在您刚刚创建的测试资产文件夹中添加您的文件。 In your Robolectric test you can read the file like this:在您的 Robolectric 测试中,您可以像这样读取文件:

val context = ApplicationProvider.getApplicationContext<Context>()
context.resources.assets.open(SOME_FILENAME)
    .bufferedReader()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM