在robolectric测试中使用的资产资产、测试中、robolectric

2023-09-06 10:07:29 作者:不愿将就

在我robolectric测试中,我想读的文件。 由于此文件只包含测试数据我已经把它在测试中的资产。

In my robolectric tests I am trying to read a file. Since this file contains just the test data I have put it in assets of the tests.

的目录结构看起来是这样的。照片 的src /主/资产/ prod_data_file 的src /测试/资产/ test_data_file

The directory structure looks like this. src/main/assets/prod_data_file src/test/assets/test_data_file

然而,当我尝试读取文件getShadowApplication()。getAssets()。打开(MY_FILE_PATH)它给了我 FileNotFoundException异常

However when I try to read the file by getShadowApplication().getAssets().open(MY_FILE_PATH) it gives me FileNotFoundException.

是否有人知道如何解决这一问题?

Does anybody know how to fix this?

推荐答案

由于我的测试只是阅读这些文件并返回文件数据为字符串我是能够做到它通过的getClass()。getClassLoader()的getResourceAsStream(MY_FILE_PATH),然后读取文件。并不真正需要阅读使用 getShadowApplication()。getAssets()。打开(MY_FILE_PATH)

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. Dont really need to read to use getShadowApplication().getAssets().open(MY_FILE_PATH).

我刚刚搬到我的测试数据文件,的src /测试/资源和它的工作。 :)

I just moved my test data files to src/test/resources and it worked. :)