Search code examples
javaandroidunit-testingandroid-studiocouchbase-lite

Unit test using CouchBase-Lite mobile without an android application context


I am trying to create a minimalist test class for testing some of my CouchBase Lite Mobile classes. I have tried mocking the Application context but have been unsuccessful.

The problem is that the CouchBase manager is accessing some of the unimplemented methods on the MockContext class.

Here are my approaches so far below:

public class ClassToTest extends TestCase {

    @Test
    public void testGetAllDocumentsBundle() throws Exception {

        try {
            Manager manager = new Manager(
                 new AndroidContext(new MockContext()), 
                 Manager.DEFAULT_OPTIONS);
        } 
        catch (Exception e) {
            Log.e(TAG, "Exception: " + e);
            assertTrue(false);
        }
    }

And:

@RunWith(AndroidJUnit4.class)
public class ItemReaderTest {

    private android.content.Context instrumentationCtx;

    @Before
    public void setUp() throws Exception {
        instrumentationCtx = InstrumentationRegistry.getContext();
    }

    ...

    @Test
    public void testGetAllDocumentsBundle() throws Exception {
        Database database = null;
        String databaseName = "test";
        try {
            Context context = new AndroidContext(instrumentationCtx);
            Assert.assertTrue(context != null);

            Manager manager = new Manager(context, Manager.DEFAULT_OPTIONS); <--- throws exception because context.getFilesDir(); return null in Couchbase Manager.java constructor
            ...
        }
    }

Has anyone been able to do this? Do I absolutely have to use an actual Activity (i.e. create an actual mobile Application and use it's context to be able to test Couchbase mobile at all?


Solution

  • I was able to successfully create the manager and database by doing this:

    class MyMockContext extends MockContext {
    
        @Override
        public File getFilesDir(){
            File f = new     
              File("/data/user/0/com.example.mypackagename/files");
            return f;
        }
    }
    

    And initializing the manager with this context:

    Context context = new AndroidContext(new MyMockContext());
    Manager manager = new Manager(context, Manager.DEFAULT_OPTIONS);
    

    However this does make the test dependent on a specific environment and hard-coded path. Perhaps there is a better solve out there...