Android/Robolectric 框架工作 - 实例化 Activity 在 getResource 上返回 null

标签 android unit-testing robolectric

这与在 Android 上使用 Robolectric 框架进行单元测试有关。我在正常运行时没有问题的代码上遇到空指针异常。我刚开始使用机器人电动工具,所以它可能非常简单。

这是测试的调用代码:

@Test
    public void testInitUtilsInitSequenceNumberIsRandom() {

    // create an activity for reference 
    InitUtils initUtils = new InitUtils();

    // do static initialization to parse questions into memory
    InitUtils.initialize(initUtils);  // <============ the call from roboelectric framework

    // retreive app state
    AppState appState = (AppState) initUtils.getApplicationContext();

    // fill in later
    fail("not implemented");

}

这是崩溃的 InitUtils 中调用的方法

/** * 将 XML 加载到 {@see mQuestions} 类成员变量中 * */

   public static void initializeQuestions(Activity activity, AppState appState)                  {

    /* create XML Parser */
    XmlResourceParser questionBatch;      
    /* local question variable */
    Question question = null;

    /* retrieve the XML for parsing */
    // ===============   This returns null  ==============================  
   questionBatch = activity.getResources().getXml(R.xml.questions);

   /* Parse the XML */
   int eventType = -1;     
   /* iterate through XML */
   while (eventType != XmlResourceParser.END_DOCUMENT) {
       if (eventType == XmlResourceParser.START_TAG) {

         /* Get the questions */
         // ================================= NPE exception ====================== 
         String strName = questionBatch.getName();
         ...etc

为了检索资源,我需要做些什么特别的事情吗?

最佳答案

我对 Robolectric 这个东西一无所知,但是 getResources() 返回 null 意味着它在框架调用 Activity.onCreate() 之前被调用。我不知道你从哪里得到这个 Activity ,但如果你在 Instrumentation 之上进行单元测试,你需要确保你的 instrumentation 线程阻塞,直到主线程完成执行,使用类似的东西:

http://developer.android.com/reference/android/app/Instrumentation.html#waitForIdleSync()

如果您正在使用 startActivitySync,这将为您完成:

http://developer.android.com/reference/android/app/Instrumentation.html#startActivitySync(android.content.Intent)

关于Android/Robolectric 框架工作 - 实例化 Activity 在 getResource 上返回 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5494210/

相关文章:

java - Mockito 在 "recording"时间捕获参数并在稍后执行时使用它

Android testCompile 项目不工作

java - 如何正确设置 api 调用以搜索用户货币指定的货币

android - 强制 android 使用方形启动器图标

android - 如何用 ActivityResultLauncher 替换 startActivityForResult 但仍然包含选项 Bundle?

android - Robolectric 与 AndroidX fragment

android - 测试驱动开发::AndroidStudio + Robolectric(Can not resolve symbol error for junit and Robolectric imports)

android - 如何让安卓应用程序始终在后台运行?

java - 如何单元测试文件访问(Java)?

apache-flex - 如何在 Flex 3 中使用本地数据模拟服务?