android - 如何使用 ActivityInstrumentationTestCase2 捕获异常?

标签 android testing robotium android-testing

我正在努力使用 ActivityInstrumentationTestCase2 类在我的 Android 应用程序的测试用例中捕获预期的异常.

我写了一个非常简单的场景来引发这个问题,一旦这个问题得到解决,我可能可以对我的应用程序做同样的事情。下面是简单场景的 fragment 。

首先,我要测试的应用程序在其 onCreate 方法中引发了 NullPointerException。

package com.example.crashtest;

import android.app.Activity;
import android.os.Bundle;

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        String s = null;
        s.trim(); // NullPointerException raised here!
        setContentView(R.layout.activity_player);
    }

}

然后,我的 ActivityInstrumentationTestCase2 类运行此测试:

package com.my.test;

import android.test.ActivityInstrumentationTestCase2;
import com.example.crashtest.MainActivity;

public class MyClassTest extends ActivityInstrumentationTestCase2<MainActivity>{

    public MyClassTest() throws ClassNotFoundException {
        super(MainActivity.class);
    }

    @Override
    protected void setUp() throws Exception {
        //setUp() is run before a test case is started. 
        super.setUp();
        try {
            getActivity(); // This calls MainActivity.onCreate().
        } catch (Exception e) {
            // Never gets here =(
        }
    }

    public void test() throws Exception {
    }
}

如果我删除对 s.trim() 的调用,那么我没有问题,但我希望能够捕获在执行测试时可能发现的任何异常。

当我执行上面的代码时,我收到以下消息:

Test failed to run to completion. Reason: 'Instrumentation 
run failed due to 'java.lang.NullPointerException''. Check device logcat for details

我怎样才能覆盖这种行为?

我发现了一个非常相似的问题 here从 2013 年开始,也没有得到回答。

最佳答案

测试引擎(在您的例子中是 ActivityInstrumentationTestCase2)就像一个沙箱。由您的代码引起的异常永远不会通过 throw e;

离开沙箱

错误处理和错误转发不是​​ ActivityInstrumentationTestCase2 的任务。每个错误都会导致测试因失败而终止。你会得到一些关于原因的描述:

Test failed to run to completion. Reason: 'Instrumentation run failed due to 'java.lang.NullPointerException''. Check device logcat for details

所以我相信,不幸的是,没有(合法的)方法来捕获测试引擎抛出的异常,处理它并恢复测试。

关于android - 如何使用 ActivityInstrumentationTestCase2 捕获异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28972419/

相关文章:

android - Webview 不加载离线缓存数据

java - EventBus - 事件生命周期的一些问题

testing - 如何在本地使用 ActiveMq 测试流

Android Robotium - 如何使用 robotium Solo 类模拟日期选择器

android - 我如何在 android 中返回到我的 gl 屏幕。我曾尝试跳出并在我的代码中使用 xml 布局

iphone - iPad/iPhone 的功能测试自动化工具?

unit-testing - 单元测试生成图像的代码的最佳方法是什么?

Android - 使用 Eclipse 使用 Robotium 的 UI 自动化

java - java (Robotium) 中的隐藏方法和类

android - 父 Activity 工具栏隐藏在子 fragment 中