使用注释条件执行方法

时间:2012-12-12 08:45:31

标签: java annotations conditional-execution

在java中我可以使用注释来条件执行方法吗?

我希望设置一些系统属性并基于该系统属性,我希望在运行时执行或不执行方法(特别是基于Ant脚本的JUnits)。

如果可以使用注释,请告诉我。

5 个答案:

答案 0 :(得分:1)

我认为你可以用Java实现它,但我建议你看看Spring AOP - 我相信这就是你要找的。

答案 1 :(得分:1)

您可以按@Category对测试进行分组,并告知正在运行的内容包括此类别。

来自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 {}

答案 2 :(得分:0)

您可以为此实现自己的TestRunner或用户AOP

答案 3 :(得分:0)

Java计算机编程语言中的注释是一种可以添加到Java源代码中的语法元数据。可以注释类,方法,变量,参数和包。

查看this

答案 4 :(得分:0)

我通过扩展BlockJUnit4ClassRunner来编写一个简单的自定义测试运行器。该运行器将从系统属性或配置文件中读取配置,以仅运行定义的测试。最简单的解决方案是排除所选方法的黑名单,因为此(默认!)运行程序的默认行为是运行每个测试。

然后就说

@RunWith(MyTestRunner.class)
public void TestClass {

// ...

}

对于实现,仅覆盖getChildren()方法可能是足够的:

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

其中filter根据属性创建的“黑名单”检查每个FrameworkMethod是否应该执行。