Constantine Gladky
Constantine Gladky

Reputation: 1263

How Can I log exception stacktrace via custom junit runner?

Hi I have custom 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);
    }
}

and custom 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);
    }

}

How can I log not only System.out.println("test fails"); but also Exception and some other information?

It seems to me that it possible to use failure, but I don't know how to.

Upvotes: 0

Views: 466

Answers (1)

Stefan Birkner
Stefan Birkner

Reputation: 24520

The Failure object has a method getException().

Upvotes: 1

Related Questions