java - How can I make sure my JUnit test method's specific cleanup always runs? -


i have junit test class has 2 test methods:

@test public void test1() {     // setup: create foo1.m     // exercise     // tear down: delete foo1.m }  @test public void test2() {     // setup: create foo2.m     // exercise     // tear down: delete foo2.m } 

for each method, make sure that, if exercise section fails reason, tear down still run. note setup , tear down code both test methods different, don't think can use junit's @before , @after annotations want.

i put try-catch blocks each test method:

@test public void test2() {     // setup: create foo2.m     try {         // exercise     } {         // tear down: delete foo2.m     } } 

but seems ugly. there way make sure test-method-specific tear down code in each test method executed, without using try-catch block?

update:

i found better solution, include here, original answer can found below. think junit 4 rules can used here:

class preparefile implements org.junit.rules.testrule {      @retention(retentionpolicy.runtime)     public @interface filename {         string value() default "";     }      @override     public statement apply(final statement statement, final description description) {         return new statement() {              @override             public void evaluate() throws throwable {                 string filename = description.getannotation(filename.class).value();                 file file = new file(filename);                 try {                      file.createnewfile();                     statement.evaluate();                 } {                     file.delete();                 }             }         };     } } 

using in test:

@rule public preparefile preparefile = new preparefile();  @test @preparefile.filename("foo1.m") public void test1() {     // exercise }  @test @preparefile.filename("foo2.m") public void test2() {     // exercise } 

here comes original answer:

you may try use @beforeclass , @afterclass annotations.

@beforeclass public static void setup() {     // setup1: create foo1.m     // setup2: create foo2.m }  @afterclass public static void teardown() {     // tear down1: delete foo1.m     // tear down2: delete foo2.m }  @test public void test1() {     // exercise }  @test public void test2() {      // exercise } 

this way can setup , tear down test cases once , framework ensures teaddown() called in case of errors well.


Comments

Popular posts from this blog

plot - Remove Objects from Legend When You Have Also Used Fit, Matlab -

java - Why does my date parsing return a weird date? -

Need help in packaging app using TideSDK on Windows -