Test注解的两个属性:expected和timeout

时间:2023-03-09 19:19:04
Test注解的两个属性:expected和timeout

JUnit4:Test文档中的解释:

  The Test annotation supports two optional parameters.

  The first, expected, declares that a test method should throw an exception.

  If it doesn't throw an exception or if it throws a different exception than the one declared, the test fails.

  For example, the following test succeeds:

@Test(expected=IndexOutOfBoundsException.class)
public void outOfBounds()
{
new ArrayList<Object>().get(1);
}

  The second optional parameter, timeout, causes a test to fail if it takes longer than a specified amount of clock time (measured in milliseconds).

  The following test fails:

@Test(timeout=100) 
public void infinity()
{
while(true);
}

  

  文档中说得比较清楚,下面再结合之前加减乘除的例子重复地解释一下,以作巩固。。

expected属性

  用来指示期望抛出的异常类型。

  比如除以0的测试:

    @Test(expected = Exception.class)
public void testDivide() throws Exception
{
cal.divide(1, 0);
}

  抛出指定的异常类型,则测试通过 。

  如果除数改为非0值,则不会抛出异常,测试失败,报Failures。

timeout属性

  用来指示时间上限。

  比如把这个属性设置为100毫秒:

@Test(timeout = 100)

  当测试方法的时间超过这个时间值时测试就会失败。

  (注意超时了报的是Errors,如果是值错了是Failures)。

附上程序例子:

  其中让加法的时间延迟500毫秒。

Calculator

package com.mengdd.junit4;

public class Calculator
{
public int add(int a, int b)
{
try
{
Thread.sleep(500);
}
catch (InterruptedException e)
{
e.printStackTrace();
} return a + b;
} public int subtract(int a, int b)
{
return a - b;
} public int multiply(int a, int b)
{
return a * b;
} public int divide(int a, int b) throws Exception
{
if (0 == b)
{
throw new Exception("除数不能为0");
}
return a / b;
}
}

  测试类代码:

  加法方法测试加入了时间限制,导致超过时间时发生错误。

  加入了除法除以零的抛出异常测试。

CalculatorTest

package com.mengdd.junit4;

import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test; import static org.junit.Assert.assertEquals;//静态导入 public class CalculatorTest
{
private Calculator cal = null; @BeforeClass
public static void globalInit()
{
System.out.println("global Init invoked!");
} @AfterClass
public static void globalDestroy()
{
System.out.println("global Destroy invoked!");
} @Before
public void init()// setUp()
{ cal = new Calculator();
System.out.println("init --> cal: " + cal); } @After
public void destroy()// tearDown()
{
System.out.println("destroy");
} @Test(timeout = 100)
public void testAdd()
{
System.out.println("testAdd");
int result = cal.add(3, 5);
assertEquals(8, result);
} @Test
public void testSubtract()
{
System.out.println("testSubtract");
int result = cal.subtract(1, 6);
assertEquals(-5, result); } @Test
public void testMultiply()
{
System.out.println("testMultiply");
int result = cal.multiply(5, 9);
assertEquals(45, result);
} @Test(expected = Exception.class)
public void testDivide() throws Exception
{
cal.divide(1, 0);
} }

参考资料

  圣思园张龙老师视频教程。

  JUnit4 chm格式文档网盘下载链接:

  JUnit 4.0:http://pan.baidu.com/share/link?shareid=539345&uk=2701745266