Conditional execution of a method using annotation

3.4k Views Asked by At

In java can I have conditional execution of a method using annotations?

I wish to have some system property set and based on that system property I wish to either execute or not execute a method (specifically ant script based JUnits) at runtime.

Please let me know if it's possible using the annotations.

5

There are 5 best solutions below

0
On

You can implement your own TestRunner or user AOP for this.

0
On

An annotation, in the Java computer programming language, is a form of syntactic metadata that can be added to Java source code. Classes, methods, variables, parameters and packages may be annotated.

Take a look at this

0
On

I think that you can implement it in Java but I suggest you to take a look on Spring AOP - I believe that this is what you are looking for.

0
On

You can group tests by @Category and tell the running to include this category.

From http://alexruiz.developerblogs.com/?p=1711

public interface FastTests { /* category marker */ }
public interface SlowTests { /* category marker */ }

public class A {
    @Category(SlowTests.class)
    @Test public void a() {}
}

@Category(FastTests.class})
public class B {
    @Test public void b() {}
}

@RunWith(Categories.class)
@IncludeCategory(SlowTests.class)
@ExcludeCategory(FastTests.class)
@SuiteClasses({ A.class, B.class })
public class SlowTestSuite {}
0
On

I'd write a simple custom test runner by extending BlockJUnit4ClassRunner. That runner would read a configuration from a system property or a configuration file to only run the defined tests. The simplest solution would be a blacklist to exclude selected methods, because the default behaviour of this (default!) runner is to run every test.

Then just say

@RunWith(MyTestRunner.class)
public void TestClass {

// ...

}

For the implementation, it could be sufficiant to just overwrite the getChildren() method:

@Overwrite
List<FrameworkMethod> getChildren() {
    List<FrameworkMethod> fromParent = super.getChildren();
    List<FrameworkMethod> filteredList = new ArrayList(filter(fromParent));
    return filteredList;
}

where filter checks for every FrameworkMethod whether it should be executed or not according to the "blacklist", that has been created based on the property.