How to catch exceptions using ActivityInstrumentationTestCase2?


I’m struggling to catch expected exceptions in test cases of my Android app using the class ActivityInstrumentationTestCase2.

I wrote a very simple scenario that is raising the issue, and once this is solved I can probably do the same thing for my app. The snippet of the simple scenario is below.

First, there is the application that I want to test, which raises a NullPointerException in its onCreate method.

package com.example.crashtest;
import android.os.Bundle;
public class MainActivity extends Activity {
protected void onCreate(Bundle savedInstanceState) {
String s = null;
.trim(); // NullPointerException raised here!

Then, there is my ActivityInstrumentationTestCase2 class that runs this test:

import android.test.ActivityInstrumentationTestCase2;
import com.example.crashtest.MainActivity;
public class MyClassTest extends ActivityInstrumentationTestCase2<MainActivity>{
public MyClassTest() throws ClassNotFoundException {
protected void setUp() throws Exception {
//setUp() is run before a test case is started.
try {
(); // This calls MainActivity.onCreate().
} catch (Exception e) {
// Never gets here =(
public void test() throws Exception {

If I remove the call to s.trim() then I have no issues, but I want to be able to catch ANY exception that I might find when executing a test.

When I execute the code above I receive the following message:

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

How can I override such behavior?

I have found a very similar question here from 2013 which wasn’t answered either.

  • You must to post comments

Test engine (in your case ActivityInstrumentationTestCase2) is like a sandbox. Exception caused by your code will never leave the sandbox via throw e;

Error Handling and Error Forwarding is not the task of ActivityInstrumentationTestCase2. Each error will cause that the test is terminated as failed. And you will get some description about the cause:

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

So i believe, unfortunately there is no (legal) way to catch an exception throwed by test engine, handle it and resume the test.

  • You must to post comments
Showing 1 result
Your Answer
Post as a guest by filling out the fields below or if you already have an account.