关闭

接口测试从零开始系列4_junit断言介绍

发表于:2011-12-13 10:24

字体: | 上一篇 | 下一篇 | 我要投稿

 作者:小刀    来源:51Testing软件测试博客

  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   "));//运行失败

   }

32/3<123>
《2023软件测试行业现状调查报告》独家发布~

关注51Testing

联系我们

快捷面板 站点地图 联系我们 广告服务 关于我们 站长统计 发展历程

法律顾问:上海兰迪律师事务所 项棋律师
版权所有 上海博为峰软件技术股份有限公司 Copyright©51testing.com 2003-2024
投诉及意见反馈:webmaster@51testing.com; 业务联系:service@51testing.com 021-64471599-8017

沪ICP备05003035号

沪公网安备 31010102002173号