Question

I'm writing some tests to test my sqllite database code. Can someone here explain if there would be a difference writing those tests using the context I get from AndroidTestCase.getContext() or using an IsolatedContext.

OTHER TIPS

For those that don't want to follow the link to the Google Group, here is the answer given there:

AndroidTestCase.getContext() returns a normal Context object. It's the Context of the test case, not the component under test.

IsolatedContext returns a "mock" Context. I put "mock" in quotes because its not a mock in the normal sense of that term (for testing). Instead, it's a template Context that you have to set up yourself. It "isolates" you from the running Android system, so that your Context or your test doesn't accidentally get outside of the test fixture. For example, an IsolatedContext won't accidentally hit a production database (unless you set it up to do that!) Note, however, that some of the methods in an IsolatedContext may throw exceptions. IsolatedContext is documented in the Developer Guide under Framework Topics > Testing, both in Testing Fundamentals and in Content Provider Testing.

Here is the Android docs on IsolatedContext.

And here is the relevant section of the Testing Fundamentals document.

I had the simple problem: I need to test my DAO class without touching the real database. So I found the IsolatedContext from docs. But finally I found the other context in the same docs: RenamingDelegatingContext might be more easier to use. Here is my test case:

public class AddictionDAOTest extends AndroidTestCase {

    @Override
    public void setUp() throws Exception {
        super.setUp();
        setContext(new RenamingDelegatingContext(getContext(), "test_"));
    }

    public void testReadAllAddictions() throws Exception {
        ImQuitDAO imQuitDAO = new ImQuitDAO(getContext());
        ...    
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top