Monday, January 2, 2012

Android unit testing with test database

In order to make your tests use a different database to your live one, have your test class extend ProviderTestCase2:

    public class MyProviderTest  extends ProviderTestCase2

Override two constructors:
    public MyProviderTest()
    {
        this(MyContentProvider.class, "my_authority_from_manifest");
    }


    public MyProviderTest(Class providerClass, String providerAuthority)
    {
        super(providerClass, providerAuthority);
    }


What this does is, in the setup() method, creates a IsolatedContext instead of the usual Context. Additionally, the base Context of this IsolatedCopntext is a RenamingDelegateContext. This class contains a field to store a prefix for the name of your database. It defauls to "test.".


In your tests, wherever you need a context object, call getMockContext(). This will return the IsolatedContext.

No comments:

Post a Comment