10
12

Hamcrest指南

作者: 舞命小丢 分类: java, 测试 0 comments

Hamcrest官方网站
Hamcrest Tutorial
介绍
Hamcrest是一个书写匹配器对象时允许直接定义匹配规则的框架.有大量的匹配器是侵入式的,例如UI验证或者数据过滤,但是匹配对象在书写灵活的测试是最常用.本教程将告诉你如何使用Hamcrest进行单元测试.
我的第一个Hamcrest测试
我们将开始写一个非常简单的JUnit 3测试,但是替换使用JUnit的assertEquals方法,我们使用Hamcrest的assertThat架构和一套标准的匹配器 ,我们需要静态导入它们:

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.*;
 
import junit.framework.TestCase;
 
public class BiscuitTest extends TestCase {
public void testEquals() {
Biscuit theBiscuit = new Biscuit("Ginger");
Biscuit myBiscuit = new Biscuit("Ginger");
assertThat(theBiscuit, equalTo(myBiscuit));
}
}

assertThat方法是一种风格化的句子进行测试断言.在这里例子中,断言问题是第一个方法参数biscuit对象.第二个方法参数是一个Biscuit对象的匹配器.在这是一个使用对象的equals方法检查一个对象等于另一个对象的匹配器.测试前Biscuit类定义了一个equals方法.
如果你在你的测试中有一个以上的测试,你可以在断言中为你的测试值包含一个标识符:

assertThat("chocolate chips", theBiscuit.getChocolateChipCount(), equalTo(10));
assertThat("hazelnuts", theBiscuit.getHazelnutCount(), equalTo(3));

9
01

Enterprise Java developers must achieve broader, deeper test coverage, going beyond unit testing to implement functional and integration testing with systematic acceptance. Next Generation Java™ Testing introduces breakthrough Java testing techniques and TestNG, a powerful open source Java testing platform.
Cédric Beust, TestNG’s creator, and leading Java developer Hani Suleiman, present powerful, flexible testing patterns that [...]

收藏 & 分享

Powered by 17fav.com