![](/img/trans.png)
[英]How to execute some code with AOP before each method of a Spring controller and have the Method object
[英]How to run some code before each JUnit @Test method individually, without using @RunWith nor AOP?
用例很简单:我想在使用@Test注释的JUnit测试中的每个方法之前运行一些样板代码和我的自定义注释(让我们称之为@Mine)。
我不想使用以下方法(括号中的解释):
我想这只留给我反思,这对我很好。 我想通过使用@Before并通过Thread.getCurrentThread()等获得当前的方法,但不知怎的,我发现这个解决方案有点脏,因为我必须在这个方法中再次制作锅炉板代码来激发反射(和避免任何不必要的代码是首先的目标)。
也许你有其他一些想法?
基于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
}
}
我会把班级分成两部分。 一个用你用@mine注释的方法和一个用其他方法注释的方法。
然后正常使用@before。
这不会增加任何标准代码,并且对于未来的开发人员也很容易理解和维护。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.