【发布时间】:2014-05-05 20:34:36
【问题描述】:
我正在尝试为我的应用程序未捕获线程异常处理程序编写单元测试,但到目前为止还没有运气。处理程序是应用程序范围的,我知道它有效。它也基于找到的代码here。但是,考虑到如果我从测试项目中抛出异常,它正在输入该代码,但它永远不会返回,我想不出一种方法来实际为其编写单元测试。这会导致我迄今为止编写的任何测试都失败。
这是我的处理程序,有人对我如何进行单元测试有任何建议吗?
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);
}
包含测试的我的项目与我的实际应用程序项目是分开的。我尝试在代码中设置标志,但是在调用异常后,我的测试已经失败,没有机会检查标志是否已设置。我想过可能在未捕获的异常处理程序中添加一个广播并触发它,或者可能使用首选项并以某种方式重新运行测试以检查首选项是否已更改,但这并不是很可靠,我想如果可能的话,避免为了测试而插入太多额外的代码。
谢谢!
【问题讨论】:
标签: java android unit-testing junit uncaught-exception