/*
*************************************************************************
* The contents of this file are subject to the Common Public License - v 1.0.
*
* Copyright (C) 2008-2009 Erich Gamma, Kent Beck, and David Saff
*
* Contributor(s):
* Leo Arias <leo.arias@openbravo.com>.
************************************************************************
*/
package com.openbravo.test.integration.junit.rules;
import org.junit.rules.MethodRule;
import org.junit.runners.model.FrameworkMethod;
import org.junit.runners.model.Statement;
/**
* A Rule class that sets up an external resource before a test (a file, socket,
* server, database connection, etc.), and guarantee to tear it down afterward.
* If an error occurs during the execution of the test, it can be handled before
* tearing down the resource.
*
* @author elopio
*
*/
public class ExternalResourceWithErrorHandling implements MethodRule {
/**
* Modifies the method-running to implement an additional test-running rule
* that sets up an external resource before a test (a file, socket, server,
* database connection, etc.), and guarantee to tear it down afterward. If
* an error occurs during the execution of the test, it can be handled
* before tearing down the resource..
*/
public final Statement apply(final Statement base, FrameworkMethod method,
Object target) {
return new Statement() {
@Override
public void evaluate() throws Throwable {
before();
try {
base.evaluate();
} catch (Throwable throwable) {
handleError(throwable);
} finally {
after();
}
}
};
}
/**
* Override to set up your specific external resource.
*
* @throws if setup fails (which will disable {@code after}
*/
protected void before() throws Throwable {
// do nothing
}
/**
* Override to handle possible errors.
*
* @throws Exception
*/
protected void handleError(Throwable throwable) throws Throwable {
throw throwable;
}
/**
* Override to tear down your specific external resource.
*/
protected void after() {
// do nothing
}
}