如何使用ActivityInstrumentationTestCase2捕获异常?

时间:2015-03-10 19:26:34

标签: android testing robotium android-testing

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

我写了一个非常简单的场景,提出了问题,一旦解决了这个问题,我可能会为我的应用做同样的事情。简单场景的片段如下。

首先,我想测试一个应用程序,它在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

如何覆盖此类行为?

我从2013年发现了一个非常类似的问题here,但也没有回答。

2 个答案:

答案 0 :(得分:1)

测试引擎(在您的情况下为ActivityInstrumentationTestCase2)就像一个沙箱。您的代码导致的异常永远不会通过throw e;

离开沙箱

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

  

测试未能完成。原因:&#39;仪表运行失败   由于&#39; java.lang.NullPointerException&#39;&#39;。检查设备logcat   细节

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

答案 1 :(得分:0)

您可以这样做:

try{
  String s = null;
  s.trim(); // NullPointerException raised here!
}catch(Error err){
  //override your behaviour here
  throw err;
}
相关问题