3)错误信息更具描述性
旧的断言语法如果断言失败,默认不会有额外的提示信息,如assertTrue(testedString.indexOf(”taobao”) > -1);如果该断言失败,只会抛出无用的错误信息,如java.lang.AssertionError:,除此之外不会有更多的提示信息。
新的断言语法会默认自动提供一些可读的描述信息,如
assertThat(testedString, containsString(”taobao”)); |
如果该断言失败,抛出的错误提示信息如下:
java.lang.AssertionError: Expected: a string containing “taobao” got: “taoba” |
4)跟Matcher匹配符联合使用更灵活强大
需要增加hamcrest包
在测试类里导入包
importstaticorg.junit.Assert.*;//assertThat跟下面的Matchers配合使用 importstaticcom.taobao.itest.matcher.Matchers.*;//增加了反射相关的匹配,比如验证两个对象的某几个属性相同 //通用匹配符 @Test publicvoidtestAssert_nomarl()throwsException { intnum = 200; String storeId ="123456"; // allOf:所有条件必须都成立 assertThat(num,allOf(greaterThan(100),lessThan(300)));//运行成功 assertThat(num,allOf(greaterThan(100),lessThan(150)));//运行失败 // anyOf:只要有一个条件成立 assertThat(num,allOf(greaterThan(100),lessThan(150)));//运行成功 assertThat(storeId,anyOf(equalTo("123456"),equalTo("1234")));//运行成功 // anything:无论什么条件 assertThat(num,anything()); //运行成功 // is:变量的值等于指定值时 assertThat(storeId,is("123456"));//运行成功 assertThat(num,is("200"));//运行成功 // not:和is相反,变量的值不等于指定值时 assertThat(storeId, notis("123456"));//运行成功 } //字符串相关匹配符 @Test publicvoidtestAssert_String()throwsException { String storeId ="assertTest"; //字符串匹配符 assertThat(storeId,containsString("assert"));//运行成功 // startsWith:字符串变量以指定字符串开头时 assertThat(storeId,startsWith("assert"));//运行成功 // endsWith:字符串变量以指定字符串结尾时 assertThat(storeId,endsWith("t"));//运行成功 // euqalTo:字符串变量等于指定字符串时 assertThat(storeId,equalTo("assertTest"));//运行成功 // equalToIgnoringCase:字符串变量在忽略大小写的情况下等于指定字符串时 assertThat(storeId,equalToIgnoringCase("assertTEst"));//运行成功 // equalToIgnoringWhiteSpace:匹配符断言被测的字符串testedString在忽略头 //尾的任意个空格的情况下等于expectedString,注意:字符串中的空格不能被忽 assertThat(storeId,equalToIgnoringWhiteSpace(" assertTest "));//运行成功 assertThat(storeId,equalToIgnoringWhiteSpace(" assert Test "));//运行失败 } |