How to catch exceptions using ActivityInstrumentationTestCase2?

0
0

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.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);
}
}

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

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 {
}
}

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
0
0

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
details

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.
Name*
E-mail*
Website