Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IsolatedContext vs. AndroidTestCase.getContext()

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.

like image 299
Arlaharen Avatar asked Jan 10 '11 09:01

Arlaharen


3 Answers

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.

like image 198
Gowiem Avatar answered Nov 13 '22 18:11

Gowiem


The answer:

http://groups.google.com/group/android-developers/browse_thread/thread/3a7bbc78258a194a?tvc=2

like image 3
fmo Avatar answered Nov 13 '22 18:11

fmo


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());
        ...    
    }
}
like image 2
cn123h Avatar answered Nov 13 '22 18:11

cn123h