根據TestRule,您需要一個與Mark unit test as an expected failure的答案非常相似的解決方案。使用@Deprecated註釋的示例(您可以在這裏使用您的示例),如果註釋存在於方法中,則可以插入代碼。 Description類包含該方法的註釋列表。
public class ExecutionTest {
public class BeforeExecution implements TestRule {
public Statement apply(Statement base, Description description) {
return statement(base, description);
}
private Statement statement(final Statement base, final Description description) {
return new Statement() {
@Override
public void evaluate() throws Throwable {
if (description.getAnnotation(Deprecated.class) != null) {
// you can do whatever you like here.
System.err.println("this will be run when the method has an @Deprecated annotation");
}
base.evaluate();
}
};
}
}
@Rule public BeforeExecution beforeExecution = new BeforeExecution();
// Will have code executed.
@Deprecated
@Test public void test1() {
// stuff
}
// won't have code executed.
@Test public void test2() {
// stuff
}
}
我不明白爲什麼@Before不能使用 –
因爲,據我所知,Before是在每個用Test註解的方法之前運行的。我的預期行爲是不同的。我希望我的自定義代碼在標有Mine註釋的方法上運行。它不能依賴於其他註釋。 –
@Before在每個方法之前都會運行。 –