【发布时间】:2011-10-04 08:10:39
【问题描述】:
我有一个测试,我希望它不应该启动
什么是好的做法:在测试中设置Ignore? @Deprecated?
我不想启动它,但有一条消息通知我应该为将来启动它进行更改。
【问题讨论】:
标签: java unit-testing junit junit4
我有一个测试,我希望它不应该启动
什么是好的做法:在测试中设置Ignore? @Deprecated?
我不想启动它,但有一条消息通知我应该为将来启动它进行更改。
【问题讨论】:
标签: java unit-testing junit junit4
我通常会使用@Ignore("comment on why it is ignored")。 IMO 评论对于其他开发人员了解为什么禁用测试或禁用多长时间(可能只是暂时的)非常重要。
编辑:
默认情况下,对于被忽略的测试,只有Tests run: ... Skipped: 1 ... 之类的信息。如何打印Ignore注解的值?
一种解决方案是自定义RunListener:
public class PrintIgnoreRunListener extends RunListener {
@Override
public void testIgnored(Description description) throws Exception {
super.testIgnored(description);
Ignore ignore = description.getAnnotation(Ignore.class);
String ignoreMessage = String.format(
"@Ignore test method '%s()': '%s'",
description.getMethodName(), ignore.value());
System.out.println(ignoreMessage);
}
}
不幸的是,对于普通的 JUnit 测试,要使用自定义的 RunListener 需要有一个注册 PrintIgnoreRunListener 的自定义 Runner:
public class MyJUnit4Runner extends BlockJUnit4ClassRunner {
public MyJUnit4Runner(Class<?> clazz) throws InitializationError {
super(clazz);
}
@Override
public void run(RunNotifier notifier) {
notifier.addListener(new PrintIgnoreRunListener());
super.run(notifier);
}
}
最后一步是注释你的测试类:
@RunWith(MyJUnit4Runner.class)
public class MyTestClass {
// ...
}
如果您使用的是 maven 和 surefire 插件,则不需要客户 Runner,因为您可以配置 Surefire 以使用自定义侦听器:
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.10</version>
<configuration>
<properties>
<property>
<name>listener</name>
<value>com.acme.PrintIgnoreRunListener</value>
</property>
</properties>
</configuration>
</plugin>
【讨论】:
Skipped: X 计数器。
@Ignore 注释值的答案
如果您使用测试套件,您可以在一处编辑所有测试用例。例如:
@RunWith(Suite.class)
@Suite.SuiteClasses({
WorkItemTOAssemblerTestOOC.class,
WorkItemTypeTOAssemblerTestOOC.class,
WorkRequestTOAssemblerTestOOC.class,
WorkRequestTypeTOAssemblerTestOOC.class,
WorkQueueTOAssemblerTestOOC.class
})
public class WorkFlowAssemblerTestSuite {
}
【讨论】: