![](/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.