我希望根据我用 Java 创建的自定义注释来执行 JUnit4 测试。此自定义注释的目的是让 JUnit4 注意到,仅当机器的平台与注释中指定的平台匹配时才应运行测试。
假设我有以下注释:
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;
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)