Reputation: 83537
I am writing JUnit tests for my Android app. I have read through the Android developer resources (testing fundamentals, Spinner example test, etc.). Now I want to test my SQLiteOpenHelper subclass independently of the Activities which use it. My idea is to extend ActivityInstrumentationTestCase2<Activity>
. Is it okay to simply use Activity
as the generic parameter or do I need a subclass? Also, am I headed in the right direction here, or is there a better way to test my SQLiteOpenHelper subclass?
Upvotes: 1
Views: 3608
Reputation: 653
For testing with Android Studio,
You should use MockContext
instead of RenamingDelegatingContext
.
If you use RenamingDelegatingContext
, You would get context as null.
For AndroidTestCase, getContext()
would return null. And for InstrumentationTestCase, getInstrumentation().getContext()
would return null.
For further information, see this answer. https://stackoverflow.com/a/29063736/1020456
Upvotes: 0
Reputation: 29722
I was looking for an answer to exactly this problem, and found this link as well as another interesting related question here:
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();
}
}
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.
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).
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.
Here is another related post where the accepted answer says pretty much the same thing:
Some useful tips in there about using ContentProvider
instead (but that's a different issue for another day).
Upvotes: 2
Reputation: 7435
following link talk about testing in android:
http://developer.android.com/tools/testing/testing_android.html
may be you have already seen it just posting it in case you have missed going through it.. it is a very good resource to learn about junit in android...
Upvotes: 0