La anotación @Rule en JUnit permite marcar campos públicos de una clase de Test que sean de tipo MethodRule (o una implementación de este).
Permite ejecutar código antes, después o en lugar del método de test, como:
Si creo una implementación de MethodRule implementaré el método public Statement apply(final Statement base, final FrameworkMethod method, final Object target) que me permite decidir que métodos interceptar, por ejemplo:
Para mi clase DummyTest:
| public class DummyTest {
@Rule public IgnoreLeadingFailure ilf = new IgnoreLeadingFailure(); @Test public void testTest() { assertTrue(false); } } |
| public class IgnoreLeadingFailure implements MethodRule {
private final static String PROPERTY_FILE_NAME = "activatedTests.properties"; private final static Properties activatedTests = new Properties(); static { try { activatedTests.load(new FileInputStream(PROPERTY_FILE_NAME)); } catch (IOException e) { // actually this is to be expected on the first run System.out.println("Couldn’t load Properties from file" + e); } } public Statement apply(final Statement base, final FrameworkMethod method, final Object target) { if (activatedTests.containsKey(getFullTestMethodName(method, target))) { return base; } else { return new Statement() { @Override public void evaluate() throws Throwable { try { base.evaluate(); activateTest(getFullTestMethodName(method, target)); } catch (Throwable t) { throw new AssumptionViolatedException( "This test never succeeded before, and failed again with: " + t.toString()); } } private void activateTest(String fullTestMethodName) { activatedTests.put(fullTestMethodName, new SimpleDateFormat().format(new Date())); try { activatedTests.store(new FileOutputStream( PROPERTY_FILE_NAME), "tests that ran successfully at least once"); } catch (IOException io) { System.out.println("failed to store properties" + io); } } }; } } private String getFullTestMethodName(final FrameworkMethod method, Object target) { return target.getClass().getName() + " " + method.getName(); } } |
Podéis leer más aquí:
http://blog.schauderhaft.de/2009/10/04/junit-rules/
http://blog.mycila.com/2009/11/writing-your-own-junit-extensions-using.html
http://cwd.dhemery.com/2011/01/what-junit-rules-are-good-for/


Deja un comentario