Skip to content

Instantly share code, notes, and snippets.

@alb-i986
Last active August 29, 2015 14:21
Show Gist options
  • Save alb-i986/096ba90d589da4d075ef to your computer and use it in GitHub Desktop.
Save alb-i986/096ba90d589da4d075ef to your computer and use it in GitHub Desktop.
Tear down resources with TestNG (naive solution)
/**
* With JUnit's @Rule, any exception thrown while closing a resource
* is automatically caught, so that all of the resource-closers can be executed.
*
* Set two breakpoints, where indicated, to see it yourself.
* If the execution stops twice, that means that all of the resource-closers have been executed,
* despite the fact the first threw an exception.
*/
public class TearDownResourcesJUnit {
String s1 = "asd1";
String s2 = "asd2";
@Rule
public ExternalResource res1 = new ExternalResource() {
@Override
protected void after() {
s1 = "s1 cleaned";
// set a breakpoint here
throw new AssertionError();
}
};
@Rule
public ExternalResource res2 = new ExternalResource() {
@Override
protected void after() {
s2 = "s2 cleaned";
// set another breakpoint here
throw new AssertionError();
}
};
@Test
public void asd() {
System.out.println("test to verify that all @Rule's are executed, even though one throws an exception");
}
}
/**
* This is an example made for showing my point in http://stackoverflow.com/a/6100111/1797282.
* The point being that TestNG @AfterMethod is not equivalent to JUnit's @Rule.
*/
public void Base {
/**
* When you have many resources to tear down,
* you will typically want to tear down as many as possible,
* not just "until the first tear down that fails".
* Therefore you need to write a try/catch for each resource.
*
* Also, you may still want the tearDown method to throw an exception,
* reporting all the errors. So you need to finish the tear down with an
* "assert that errors is empty".
*/
@AfterClass
public void tearDown() {
List<Throwable> errors = new ArrayList<>();
try {
resource.close();
} catch (Throwable t) {
errors.add(t);
}
try {
service.stop();
} catch (Throwable t) {
errors.add(t);
}
try {
pageServer.close();
} catch (Throwable t) {
errors.add(t);
}
org.junit.Assert.assertThat(errors, is(empty()));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment