java - 如何引入Android Context来测试?

标签 java android maven junit

我有一个从 assets 目录读取属性的类。这个类的构造函数有Context。我想为这个类编写测试,但我真的不知道如何在 Android 测试中获取上下文。

public class PropertyLoader {

    private Context context;
    private Properties properties;

    public PropertyLoader(Context context) {
        this.context = context;
        properties = new Properties();
    }

    public Properties getProperties(String FileName) {
        ...
    }
}

测试类

public class PropertyLoaderTest extends InstrumentationTestCase {
    @Test
    public void testSimple() {
        Context context = getInstrumentation().getContext();
        PropertyLoader propertyLoader = new PropertyLoader(context);
    }
}

我收到以下异常

junit.framework.AssertionFailedError: Exception in constructor: testSimple (java.lang.RuntimeException: Stub!

最佳答案

在 Android 模拟器或设备上运行测试。

您在桌面上使用的 android.jar 没有任何实现。那里的所有方法都会抛出 RuntimeException: Stub!

或者,从代码中删除所有 Android 依赖项,以便您无需导入 android.jar 即可运行测试。

关于java - 如何引入Android Context来测试?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23652496/

相关文章:

android - 菜单项不可见

java - 为什么我的 Maven 不使用定义的 BOM?

java - Selenium 中的线程 "main"java.lang.NullPointerException 中出现异常

java - 如何使用 Apache HttpComponentst 创建和发布多部分/混合 http 请求?

java - hibernate 错误: No Persistence provider for EntityManager named my-unit

java - Facebook离线访问一步一步

仅在 Google Pixel 6P 上发生 Android native 崩溃

java - Collections.synchronizedSortedMap 与 ConcurrentSkipListMap 用于并发使用的排序映射

java - 接下来的编辑文本字段遵循其自身

java - Maven Java GAE编译错误