我正在尝试创建一个极简测试类来测试我的一些 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 移动设备?
最佳答案
我能够通过这样做成功创建管理器和数据库:
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);
但是,这确实使测试依赖于特定环境和硬编码路径。也许有更好的解决方案......
关于java - 使用 CouchBase-Lite 移动设备进行单元测试,无需 Android 应用程序上下文,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42872663/