多语言展示
当前在线:888今日阅读:23今日分享:25

TDD之Hamcrest系列1---一般匹配

Hamcrest其实不能做单元测试,做单元测试的框架是Junit。Hamcrest是个匹配器,可以让我们更方便,更高效的写出我们预期的单元测试Junit是部车,Hamcrest就是一个很的坐垫喽本文就来分享一下Hamcrest的一般匹配
工具/原料
1

IntelliJ IDEA

2

Hamcrest

3

junit

方法/步骤
1

需要的jar:junit-4.11.jarhamcrest-core-1.3.jarhamcrest-library-1.3.jar//这个Jar也是必需的哦。里面有不少有用的方法jar的版本可以根据自己的需要进行调整

2

匹配器allOf的使用。allOf:所有条件都满足才为true。描述的是且的关系Code:package tdd;import org.junit.Test;import static org.hamcrest.MatcherAssert.assertThat;import static org.hamcrest.Matchers.greaterThan;import static org.hamcrest.Matchers.lessThan;import static org.hamcrest.core.AllOf.allOf;/** * Created by MyWorld on 2016/3/18. */public class HamcrestMatch {    @Test    public void commonMatch() {        int actual = 3;        assertThat(actual, allOf(greaterThan(0), lessThan(5)));    }}

3

匹配器anyOf的使用。anyOf:或的关系。只要其中一个条件满足,就返回trueCode:@Testpublic void commonMatch() {      assertThat(-1, anyOf(greaterThan(0), lessThan(5)));     assertThat(6, anyOf(greaterThan(0), lessThan(5)));}

4

匹配器anything的使用。anything:就是无所谓了。在mock对象方法的入参时很有用示例,就简单点吧Code:@Testpublic void commonMatch() {    assertThat(-1, anything());    assertThat(6, anything());}

5

匹配器is的使用。其它上一篇已经讲过了,这一次就更深入,更专业的描述下吧is:可以 认为是java中的equals方法,如果前后两个对象equals了,则返回true和直接使用assertEquals的区别就是,如果用例失败时,会把actual和expected的值都打印出来Code:@Testpublic void commonMatch() {    assertThat(-1, is(-1));    String actual = 'commonMatch';    assertThat(actual, is(new String('commonMatch')));}

6

匹配器not的使用。not:认为是java中的!中。非,在匹配器中的描述Code:@Testpublic void commonMatch() {    assertThat(-1, not(1));    String actual = 'commonMatch';    assertThat(actual, not(new String('common')));}

推荐信息