在没有 android 应用程序上下文的情况下使用 CouchBase-Lite 移动设备进行单元测试

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

我正在尝试创建一个极简测试 class 来测试我的一些 CouchBase Lite Mobile classes。我曾尝试模拟应用程序上下文,但没有成功。

问题是 CouchBase 管理器正在访问 MockContext class 上的一些未实现的方法。

下面是我的方法:

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);
        }
    }

并且:

@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
            ...
        }
    }

有人能做到吗?我是否绝对必须使用实际的Activity(即创建一个实际的移动应用程序并使用它的上下文来完全测试 Couchbase 移动设备?

通过这样做,我能够成功地创建管理器和数据库:

class MyMockContext extends MockContext {

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

并使用此上下文初始化管理器:

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

然而,这确实使测试依赖于特定环境和硬编码路径。也许有更好的解决办法...