如何将数据库测试装置从单元测试应用程序传输到设备
我正在编写一个 Android JUnit 测试,想要复制/重置一个测试夹具文件(它是一个 SQLite 数据库文件)。如果我在主应用程序中,我知道我可以将该文件放在资产目录中并使用 getResources().getAssets().open(sourceFile)
但是,此 API 似乎在 ActivityInstrumentationTestCase2
类中不可用。
有没有一种简单的方法可以从测试 PC 复制文件,或者我应该在设备上保留测试夹具的新副本并将其复制到临时文件上?
谢谢!
I'm writing an Android JUnit test and want to copy/reset a test fixture file (it's an SQLite database file.) If I were within the main application, I know I could just place the file in the assets directory and use getResources().getAssets().open(sourceFile)
However, this API appears to be unavailable from the ActivityInstrumentationTestCase2
class.
Is there an easy way to copy a file over from the testing PC, or should I just keep a fresh copy of a test fixture on the device and copy it over a temporary file?
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
测试应用程序和主应用程序中的资源可以在仪器测试用例中单独访问。如果要访问测试项目本身的 res/raw 或 assets 文件夹中的资源,可以使用
要访问正在测试的应用程序(“目标”应用程序)中的资源,请使用
注意,但是,您永远不能修改assets文件夹中的文件;
返回一个输入流。没有办法修改该文件。这是因为资产被压缩存储在 APK 内,并且根本不可写。
如果您想要做的是修改您正在测试的 Activity 使用的文件的路径,您应该使用 ActivityUnitTestCase 和 setActivityContext() 与RenamingDelegatingContext。这允许您通过指定目录前缀将上下文中的文件和数据库访问重定向到新目录。您甚至可以使用 更复杂的构造函数来包装大多数操作的目标上下文,但使用测试应用程序的上下文进行文件操作,因此该活动将访问存储在测试应用程序而不是主应用程序中的文件,但仍使用主应用程序中的其他资源。
The resources in your test application and your main application are accessible separately in an instrumentation test case. If you want to access resources that are in the res/raw or assets folder of the test project itself, you can use
To access resources in the application being tested (the "target" application), use
Note, however, that you can never modify files in the assets folder;
returns an InputStream. There's no way to modify the file. That's because assets are stored compressed inside the APK, and are not really writeable at all.
If what you want to do is modify the path to the files the Activity you're testing uses, you should use ActivityUnitTestCase and setActivityContext() with a RenamingDelegatingContext. This allows you to redirect file and database access in a context to a new directory by specifying a directory prefix. You can even use the more complex constructor to wrap the target context for most operations, but use your test application's context for file operations, so the activity will access files stored in the test application rather than the primary application but still use other resources in the primary application.
为了实现这一点,我所做的(以一种不太优雅的方式)是将测试夹具复制到我的设备(或模拟设备)上。我将其命名为“cleantestdatabase.db”。然后在测试代码中,我将其复制到“testdatabase.db”,以便我可以通过测试对其进行修改,但将其重置为已知状态。这是代码:
What I've done to accomplish this (in a not very elegant way) is to copy the test fixture onto my device (or emulated device.) I named it "cleantestdatabase.db." Then in the test code, I copy it to "testdatabase.db," so that I can modify it with my tests but reset it to a known state. Here's the code: