【测试之道】深刻探索:单元测试之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 
    }
}
相关文章
相关标签/搜索