【測試之道】深刻探索:單元測試之Ignnore測試和TimeOut測試

相關文章

Ignoring tests

若是出於某種緣由,您不但願測試失敗,您只但願它被忽略,您暫時禁用一個測試。能夠在方法上使用@Ignnore 註解。 ignore 一個測試在JUnit中是能夠編輯評論的一種測試方法使用@Ignore註解,或者,刪除@Test註解;可是測試的時候就不會報告有這個測試方法。然而,你在@Test前或後添加@Ignore 註解,測試的runners,能夠報告有多少個被忽略的測試方法,以及運行的測試數量和失敗的測試數量,忽略這個測試方法。 注意:@Ignore 能夠有一個能夠選擇的參數,你能夠記錄爲何y單元測試

@Ignore("Test is ignored as a demonstration")
@Test
public void testSame() {
   assertThat(1, is(1));
}

Timeout for tests

測試「失控」或佔用太長時間,可能會自動失敗。有實施該行爲的兩個選項:測試

  • 在 @Test 參數中設置超時時間
  • Timeout Rule 設置超時時間

@Test參數設置超時時間

您能夠選擇指定毫秒超時,若是測試方法比毫秒數長,則致使測試方法失敗。若是超過了時間限制,則失敗是由拋出的異常觸發的. @Test 參數只會應用在單個註解的方法ui

@Test(timeout=1000)
public void testWithTimeout() {
  ...
}

這是經過在單獨的線程中運行測試方法來實現的。若是測試運行超過規定的超時時間,測試將失敗,JUnit將中斷線程運行測試。若是在執行可中斷操做時測試超時,則運行測試的線程將退出(若是測試處於無限循環中,運行測試的線程將永遠運行,而其餘測試繼續執行)。.net

Timeout Rule

超時規則對類中的全部測試方法應用相同的超時,而且除了單個測試註釋中的超時參數指定的超時以外,當前還將執行此超時。:線程

import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.Timeout;

public class HasGlobalTimeout {
    public static String log;
    private final CountDownLatch latch = new CountDownLatch(1);

    @Rule
    public Timeout globalTimeout = Timeout.seconds(10); // 10 seconds max per method tested

    @Test
    public void testSleepForTooLong() throws Exception {
        log += "ran1";
        TimeUnit.SECONDS.sleep(100); // sleep for 100 seconds
    }

    @Test
    public void testBlockForever() throws Exception {
        log += "ran2";
        latch.await(); // will block 
    }
}
相關文章
相關標籤/搜索