我希望我的JUnit4测试根据我用 Java创建的自定义注释来执行.此自定义注释的目的在于JUnit4注意,只有当机器的平台与注释中指定的平台匹配时,测试才应该运行. 说我有以下注释: public
说我有以下注释:
public @interface Annotations { String OS(); ... }
和以下测试:
public class myTests{ @BeforeClass public setUp() { ... } @Annotations(OS="mac") @Test public myTest1() { ... } @Annotations(OS="windows") @Test public myTest2() { ... } @Annotation(OS="unix") @Test public myTest3() { ... } }
如果我要在Mac机器上执行这些测试,那么只有myTest1()应该被执行,其余的应该被忽略.不过,我目前坚持要如何实施.如何让JUnit读取我的自定义注释,并检查测试是否应该运行.
您可以使用类别,也可以实现自己的自定义JUnit转轮.扩展默认的JUnit转轮是非常简单的,并允许您定义要以任何您想要的方式运行的测试列表.这包括仅查找具有特定注释的测试方法.我包括下面的代码示例,你可以使用它们作为你自己实现的基础:注解:
@Retention(RetentionPolicy.RUNTIME) public @interface MyCustomAnnotation { String OS(); }
自定义跑步者类:
public class MyCustomTestRunner extends BlockJUnit4ClassRunner { public MyCustomTestRunner(final Class<?> klass) throws InitializationError { super(klass); } @Override protected List<FrameworkMethod> computeTestMethods() { // First, get the base list of tests final List<FrameworkMethod> allMethods = getTestClass() .getAnnotatedMethods(Test.class); if (allMethods == null || allMethods.size() == 0) return allMethods; // Filter the list down final List<FrameworkMethod> filteredMethods = new ArrayList<FrameworkMethod>( allMethods.size()); for (final FrameworkMethod method : allMethods) { final MyCustomAnnotation customAnnotation = method .getAnnotation(MyCustomAnnotation.class); if (customAnnotation != null) { // Add to accepted test methods, if matching criteria met // For example `if(currentOs.equals(customAnnotation.OS()))` filteredMethods.add(method); } else { // If test method doesnt have the custom annotation, either add it to // the accepted methods, or not, depending on what the 'default' behavior // should be filteredMethods.add(method); } } return filteredMethods; } }
样品测试类:
@RunWith(MyCustomTestRunner.class) public class MyCustomTest { public MyCustomTest() { super(); } @Test @MyCustomAnnotation(OS = "Mac") public void testCustomViaAnnotation() { return; } }