如何通过自定义junit runner记录异常堆栈跟踪?

时间:2012-02-29 16:27:50

标签: exception junit

您好我有自定义junit runner

public class InterceptorRunner extends BlockJUnit4ClassRunner {

    @Retention(RetentionPolicy.RUNTIME)
    @Target(ElementType.TYPE)
    public @interface InterceptorClasses {
        public Class<?>[] value();
    }

    public InterceptorRunner(Class<?> klass) throws InitializationError {
        super(klass);
    }

    @Override
    public Statement methodInvoker(FrameworkMethod method, Object test) {
        InterceptorStatement statement = new InterceptorStatement(super.methodInvoker(method, test));
        InterceptorClasses annotation = test.getClass().getAnnotation(InterceptorClasses.class);
        Class<?>[] klasez = annotation.value();
        try {
            for (Class<?> klaz : klasez) {
                statement.addInterceptor((Interceptor) klaz.newInstance());
            }
        } catch (IllegalAccessException ilex) {
            ilex.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        }
        return statement;
    }

    @Override
    public void run(RunNotifier notifier) {
        FailListener listener = new FailListener();
        notifier.addListener(listener);
        super.run(notifier);
        notifier.removeListener(listener);
    }
}

和自定义侦听器

public class FailListener extends RunListener {

    @Override
    public void testFailure(Failure failure) throws Exception {
        System.out.println("test fails");
        super.testFailure(failure);
    }

    public void testStarted(Description description) throws Exception {
        System.out.println("Test started");
        super.testStarted(description);
    }

}

如何不仅记录System.out.println(“测试失败”);还有Exception和其他一些信息吗?

在我看来,有可能使用失败,但我不知道如何。

1 个答案:

答案 0 :(得分:1)

Failure对象有一个方法getException().