I'm trying to write a unit test for my applications uncaught thread exception handler, but have had no luck so far. The handler is application wide, and I know it works. It was also based around code found here. However I can't think of a way to actually write a unit test for it, considering that if I throw an exception from my test project it is entering that code, but it never returns. This causes any test that I've so far written to fail out.
Here is my handler, does anyone have any suggestions how I can unit test this?
public class MyApplication extends Application {
// uncaught exception handler variable
private final UncaughtExceptionHandler defaultUEH;
// handler listener
private final Thread.UncaughtExceptionHandler _unCaughtExceptionHandler = new Thread.UncaughtExceptionHandler() {
@Override
public void uncaughtException(Thread thread, Throwable ex) {
// Try restarting the application if an uncaught exception has
// occurred.
PendingIntent myActivity = PendingIntent
.getActivity(getApplicationContext(), 192837, new Intent(
getApplicationContext(), MainGui.class), PendingIntent.FLAG_ONE_SHOT);
AlarmManager alarmManager;
alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, 15000, myActivity);
System.exit(2);
// re-throw critical exception further to the os (important)
defaultUEH.uncaughtException(thread, ex);
}
};
public MyApplication() {
defaultUEH = Thread.getDefaultUncaughtExceptionHandler();
// setup handler for uncaught exception
Thread.setDefaultUncaughtExceptionHandler(_unCaughtExceptionHandler);
}
My project that contains the tests is separate from my actual application project. I've tried setting flags in the code, but after the exception is called, my test has already failed and there is no opportunity to check that flags have been set. I've thought of maybe adding a broadcast in the uncaught exception handler and triggering off that, or maybe to use preferences and somehow re-run the test to check the preference has changed, but that doesn't seam very reliable and I would like to avoid too much extra code that is just inserted for the sake of testing if that is possible.
Thanks!