2013-11-05 69 views
1

我有幾個測試,並使用junit。在我所有的測試文件中,我都有junit @Rule語句。如:重構來自測試的JUnit規則

public @Rule 
TestWatcher resultReportingTestWatcher = new TestWatcher(this); 

這和其他幾個語句存在於我的所有測試文件中。代碼的這種重複使我有點困擾,因爲我認爲這些代碼行可以移到一個單獨的地方,並可以從那裏使用。

我不太確定是否可以這樣做,因爲我對junit很新。 需要giudence。

回答

1

您可以把常用的Rule S IN父類:

public class AbstractTest { 
    @Rule public SomeRule someRule = new SomeRule(); 
} 
public class YourTest extends AbstractTest { 
    @Test public void testMethod() { 
     someRule.blah(); 
     // test some things 
    } 
} 
+0

謝謝你的回覆。另外,這個'@ Rule'語句可以在某些情況下使用嗎?例如:我希望只有在某些條件爲真的情況下才能執行此語句。 –

+0

不,它不能--JUnit在運行測試(或者任何'@ Before'方法)之前反射地通過你的測試類並調用任何'@ Rule's。 – pobrelkey

+0

您可以創建自己的規則,它考慮條件。 –