- 论坛徽章:
- 0
|
源于Java Power Tools一书,此部分主要介绍一些JUNIT 4的一些新特性.总感觉自己过于的纸上谈兵,希望以后要注意了...一直没有进行过TDD的开发,虽然了解一些关于测试的知识.
1.测试类以Test结尾,测试方法以test开头.
2.一个方法上加上@Test表明此方法为测试方法,而此方法的类不一定要继承TestCase.
3.The @Before annotation indicates a method that needs to be called before each test, effectively replacing the setup() method of JUnit 3.x.
即关于@Before的注释作用相当于junit 3中的setup() .当然就有@After,也就相当于teardown()了.
4.Methods annotated with @BeforeClass will be invoked just once, before any of the unit tests are executed
也就是注释@BeforeClass,它只执行一次,所以区别于上面的@Before(每个测试方法执行前执行一次).此方法要求静态.
同样的有methods annotated with @AfterClass are executed only when all of the tests have been completed.
根据个人实验观察得到如下结果:
有多少个方法,其构造方法运行多少次,且@BeforeClass先于构造方法执行.也就是说对于每个测试方法都是类从头到尾执行一次.
[email=.@BeforeClass]@BeforeClass[/email]
不能用于构造方法.
5.关于测试类运行时间的注释,@Test(timeout=100),即表示此方法必须要在0.1秒内执行完毕,不然错误.
不过根据个人实验发现有点误差吧,但如果要求不是十分准确的话,还是可以的.
6.@Test(expected = IllegalArgumentException.class)
用来进行异常判断处理,预期可能出现的异常.
7.大量数据的测试
接下来在构造函数中获得上面的数据.
8.Using assertThat and the Hamcrest Library
assertThat(calculatedTax, is(0.0));
与assertEquals类似,只是易读.
assertThat(result, equalTo("red"));
assertThat(color, anyOf(is("red"),is("green"),is("yellow")));
@RunWith(Parameterized.class)
public class TaxCalculatorTest {
@Parameters
public static Collection data() {
return Arrays.asList(new Object[][]{
/* Income Year Tax */
{ 0.00, 2006, 0.00},
{ 10000.00, 2006, 1950.00},
{ 20000.00, 2006, 3900.00},
{ 38000.00, 2006, 7410.00},
{ 38001.00, 2006, 7410.33},
{ 40000.00, 2006, 8070.00},
{ 60000.00, 2006, 14670.00},
{100000.00, 2006, 30270.00},
});
}
9.JUnit 4 Theories
首先定义一组数据,然后利用@assumeThat 选择所要测试的数据.
The developer first specifies a set of data points for testing the theory.
@DataPoint public static int YEAR_2007 = 2007;
@DataPoint public static int YEAR_2008 = 2008;
The next step is to define your assumptions using the @assumeThat annotation.
assumeThat(year, is(2007));
书上的一个例子(做了修改简化):
@RunWith(Theories.class)
public class TaxCalculatorTheoryTest {
//定义数据
@DataPoint public static int YEAR_2007 = 2007;
@DataPoint public static int YEAR_2008 = 2008;
@DataPoint public static BigDecimal INCOME_1 = new BigDecimal(0.0);
@DataPoint public static double INCOME_2 = 0.01;
@DataPoint public static double INCOME_3 = 100.0;
@DataPoint public static double INCOME_4 = 13999.99;
@DataPoint public static double INCOME_5 = 14000.0;
@SuppressWarnings("unchecked")
@Theory //取代了@Test
public void lowTaxRateIsNineteenPercent(int year, double income) {
assumeThat(year, is(2007));
assumeThat(income, allOf(greaterThan(0.00),lessThan(14000.00)));
//获取需要测试的数据
TaxCalculator calculator = getTaxCalculator();
double calculatedTax = calculator.calculateIncomeTax(year, income);
double expectedIncome = calculatedTax * 1000/195;
assertThat(expectedIncome, closeTo(income,0.001));
}
}
上面的测试会对2007年income 2到4进行测试.
关于钱的数据类型,最好用such as BigDecimal or a dedicated Money class表示,而不是double.
本文来自ChinaUnix博客,如果查看原文请点:http://blog.chinaunix.net/u/31712/showart_653568.html |
|