【问题标题】:Unit test using CouchBase-Lite mobile without an android application context在没有 android 应用程序上下文的情况下使用 CouchBase-Lite 移动设备进行单元测试
【发布时间】:2017-03-18 09:33:53
【问题描述】:

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

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

以下是我目前的方法:

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 移动设备?

【问题讨论】:

    标签: java android unit-testing android-studio couchbase-lite


    【解决方案1】:

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

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

    但是,这确实使测试依赖于特定环境和硬编码路径。也许那里有更好的解决方案......

    【讨论】:

    • 你好@Willeman,我只是想问一下你是否找到了更好的选择。另外,附带说明一下,如果它解决了您的问题,您应该接受答案(即使您写了它)。
    • @Alator 嗨,感谢您的提示。想我当时可能没有特权。完毕。不幸的是,自从:/
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-10-03
    • 2021-10-30
    • 2015-06-30
    • 1970-01-01
    • 1970-01-01
    • 2021-02-23
    • 2011-05-03
    相关资源
    最近更新 更多