Creating a MockContext() to test android

2,083 views
Skip to first unread message

fernan.do

unread,
Apr 5, 2008, 3:44:53 PM4/5/08
to Android Internals
Hi Everyone,
I am trying to test my database CRUD methods. To do so I need to
create a Context since Android's openDatabase and so on are invoked
from the Context class. I was sure that one way to do so was to create
a MockContext() and use that to invoke the mehtods. This is not
working, the following piece of code gives me an
UnsuportedOperationException:

private MockContext context=new MockContext();
mDb = context.openDatabase(DATABASE_NAME, null);

I am not sure why this is happening, since on the references pages
these methods seem to be supported but since we do not have access to
the source I am not really sure what is happening. Any one has run
into a problem like this?

Thanks!

hackbod

unread,
Apr 7, 2008, 2:20:36 AM4/7/08
to Android Internals
A MockContext is a completely stubbed out context, so all of the
methods on it throw UnsupportedException(). If there is some specific
piece of functionality on Context that you want to mock, you make a
subclass of MockContext and hand that to the code to be tested,
allowing it to call back on your mock implementation.

For your specific case of openDatabase(), you will need to either make
a subclass that implements that method as you desire (for example
making an in-memory database), or get a real context and use that.

fernan.do

unread,
Apr 28, 2008, 8:02:10 AM4/28/08
to Android Internals
Hi hackbod,
Thanks for your reply and sorry for the delay in answering. Your
response makes perfect sense, but as you imagine I do not really want
to create implementations for all the mock methods. I would much
rather use a real context in my JUnit tests. You mentioned I sould get
a real context and use that. Do you know how I can pass or get a real
context to my JUnit class DbHelperTest?

public class DbHelperTest extends TestCase {

/**
* Set-up code for tests
*/
private MockContext context=new MockContext();
DbHelper mDbHelper=new DbHelper(context);

public void testCreateDatabase (){
//What other tests can I do? can I check the database is created?
try {
mDbHelper.open();
} catch (SQLException ex) {
fail(ex.getMessage());
}

//Database should have been created, proceed to check this is the
case
//but I can't check without calling the name...
}

}

Thanks so much!
Fernan.do
Reply all
Reply to author
Forward
0 new messages