2012-02-01 125 views
3

我有兩個JUnit4測試類說MyTest1,MyTest2每個有幾個測試方法。 其實這些都是Selenium JUnit TestCases。如何在每個TestCase之間延遲執行JUnit TestSuite?

在MyTest1.someMethodInsertingDate()我會插入一些數據到數據庫,這將需要一些時間來處理。

在MyTest2.validateProcessedData()我需要驗證插入到第一個測試方法中的已處理數據是否有效。

我知道測試方法/案例之間的耦合並不是一個好的做法。但是我正在編寫SeleniumTests來自動化UI上的用戶操作,所以我必須這樣做。

我正在使用MyTestSuite和@RunWith執行這兩個TestCase & @SuiteClasses。

現在我怎麼能告訴JUnit執行MyTest2 TestCase有一些延遲,比如說1分鐘。

回答

2

我想你沒有得到的答案(至少不是一個你想要的)這個問題,因爲它通常被認爲是不好的做法,在一個測試套件依靠這些機制。如果你對這些類型的依賴性相互依賴,你的測試將變得非常難以維護,並且可能(很可能會)會導致你在以後的調試中遇到困難。

你可能會抽象出第一個測試,第二個測試可能會擴展它。然後,第二個測試將使用其設置中的通用功能(可能使用不同的數據)。這應該允許你同時運行測試,因爲每個測試都是一個原子實體。

+0

你是對的。耦合黑白測試用例是一種不好的做法。所以最後我將相關的測試方法轉移到私有方法中,從測試用例中將sleep()放入它們之間。 – 2012-02-03 02:22:59

0

您可以通過在每種測試方法的末尾添加一些東西來睡覺腳本。
在PHP:

sleep(60);
0

你可以這樣你的數據庫代碼後,誘導Java中的第一個測試情況下,一些等待:

長END3 = System.currentTimeMillis的()+ 6000;

 while(System.currentTimeMillis()<end3) 
     { 
      // Do nothing here Just time pass. 
     } 

這將確保Java代碼在DB代碼之後等待6000毫秒,並且應該足以添加數據。您可以根據數據大小調整時間。

1

由於我們希望所有人都同意這是一般不好的做法,所以也有例外。 爲了說明顯而易見的問題,我們不是談論單元測試,而是集成測試(JUnit可能不是正確的工具,但我沒有找到更好的東西)

我也在做Selenium測試。我對第三方測試服務器進行集成測試,如果我在沒有sleep的情況下運行測試,那麼行爲是隨機的。

這是可能的解決方案之一,請注意,這只是通過運行測試一次:

public class SleepySuite extends Suite { 
    private final Logger log = LoggerFactory.getLogger(SleepySuite.class); 
    private final Integer defaultSleepSec = 0; 
    private final Integer sleepSec; 

    public SleepySuite(Class<?> klass, RunnerBuilder builder) throws InitializationError { 
     super(klass, builder); 
     sleepSec = initSleep(klass); 
    } 

    private Integer initSleep(Class<?> klass) { 
     SleepSec ts = klass.getAnnotation(SleepSec.class); 
     Integer sleep = defaultSleepSec; 
     if (ts != null) { 
      sleep = ts.value(); 
      log.debug("Configured with sleep time: {}s", sleep); 
     } 
     return sleep; 
    } 

    @Retention(RetentionPolicy.RUNTIME) 
    @Target(ElementType.TYPE) 
    @Inherited 
    public @interface SleepSec { 
     public int value(); 
    } 

    /** 
    * @see org.junit.runners.Suite#runChild(org.junit.runner.Runner, org.junit.runner.notification.RunNotifier) 
    */ 
    @Override 
    protected void runChild(Runner runner, RunNotifier notifier) { 
     super.runChild(runner, notifier); 
     //Simply wrapped Thread.sleep(long) 
     TestUtils.sleep(sleepSec); 
    } 
} 

您的套房〔實施例:

@RunWith(SleepySuite.class) 
@Suite.SuiteClasses({ 
    Some.class, 
    SomeOther.class 
}) 
@SleepySuite.TimeoutSec(30) 
public class YourSuite{ 
} 
1

您可以使用簡單的「@Before」註解。 它應該在每次開始測試時延遲執行線程。

例子:

@Before 
public void initialise() throws InterruptedException { 
    Thread.sleep(2000); 
} 
相關問題