更新时间:2023-11-19 13:53:28
我一直在寻找的答案,正是这个问题,并发现此链接,以及另外一个有趣的相关的问题在这里:
I was looking for an answer to exactly this problem, and found this link as well as another interesting related question here:
由@Pietro接受的答案的 显示了一些简单的code,使用基本 AndroidTestCase
,这将直接有助于回答这个问题。
The accepted answer by @Pietro shows some simple code, using a basic AndroidTestCase
, which will help directly to answer the question.
public class DatabaseTest extends AndroidTestCase {
private MyDatabase db;
public void setUp(){
RenamingDelegatingContext context
= new RenamingDelegatingContext(getContext(), "test_");
db = new MyDatabase(context);
}
public void testAddEntry(){
// Here I have my new database which is not connected to the standard database of the App
}
public void tearDown() throws Exception{
db.close();
super.tearDown();
}
}
我是在它看起来多么简单的快乐。在我来说,我是新来的Android测试,所以即使是简单的东西,此刻似乎很难。
I was happy at how simple it looks. In my case I'm new to Android testing, so even the simple stuff seems difficult at the moment.
但在有趣的部分这是关键,是使用的 RenamingDelegatingContext
类作为你的背景,而不是仅仅使用一个正常的范围内。这似乎是建立在由@Jens提出的意见。
But the interesting part which is key, is using the RenamingDelegatingContext
class as your "context" instead of just using a normal context. This seems to build on the comments made by @Jens.
本类包装的特定环境下和代表大多数操作到这方面。有用的部分是它用重命名的数据库/文件名执行数据库和文件操作
(看在线文档)。
This class wraps a given context and delegates most operations to that context. The useful part is that it performs database and file operations with a renamed database/file name
(see documentation online).
这可以让您的测试code使用的数据库的实际不同的实例到生产code - 至少在我的情况下,这将是有益的。
This allows your TEST code to use an actual different instance of the database to your PRODUCTION code - at least in my case this is going to be useful.
下面是另一个相关的帖子里公认的答案说,pretty很多类似的话:
Here is another related post where the accepted answer says pretty much the same thing:
在有一些有用的提示关于使用的ContentProvider
代替(但这是另一天的不同的问题)。
Some useful tips in there about using ContentProvider
instead (but that's a different issue for another day).