Łuk*_*man 4 java reflection junit aop
用例很简单:我想在使用@Test注释的JUnit测试中的每个方法之前运行一些样板代码和我的自定义注释(让我们称之为@Mine).
我不想使用以下方法(括号中的解释):
我想这只留给我反思,这对我很好.我想通过使用@Before并通过Thread.getCurrentThread()等获得当前的方法,但不知怎的,我觉得这个解决方案有点脏,因为我必须在这个方法中再次制作锅炉板代码来激发反射(和避免任何不必要的代码是首先的目标).
也许你有其他一些想法?
Mat*_*ell 11
基于TestRule,您需要一个非常类似于Mark单元测试答案的解决方案作为预期的故障.使用@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
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5941 次 |
| 最近记录: |