assertThat的一般句型为:

assertThat([value],[matcher statement]);

这种断言的优点有:

1.更具有可读性:该语法允许我们以“主谓宾”的方式来思考(assert "x is 3"), 而不是 assertEquals(assert "equals 3 x")。

2.易组合性:任何Matcher语句可以是否定的(not(s)),组合的(either(s).or(t)),映射到组合(each(s)),或者用自定义组合(afterFiveSeconds(s))。

3.易读的失败提示信息。

import static org.junit.Assert.*;  
import static org.hamcrest.CoreMatchers.*;  
import org.junit.Test;  
  
public class AssertThat {  
    @Test  
    public void testMessage(){  
        String s=new String("hello world");  
          
        assertTrue(s.contains("i")||s.contains("happy"));  
        // failure message:   
        // java.lang.AssertionError:  
        assertThat(s,anyOf(containsString("i"),containsString("happy")));  
        //failure message:  
        //java.lang.AssertionError:   
        //Expected: (a string containing "i" or a string containing "happy")  
        //  but: was "hello world"  
    }  
}  

 

4.开发人员可以通过实现Matcher接口,定制自己想要的匹配符。当开发人员发现自己的某些测试代码在不同的测试中重复出现,经常被使用,这时就可以自定义匹配符,将这些代码绑定在一个断言语句中。

junit.jar自带了一些Matcher,定义在org.junit.matchers.JUnitMatchers。为了使用更多的Matcher,我们可以导入hamcrest-core.jar和hamcrest-library.jar。这是JUnit第一次使用第三方的类。使用之前需要静态引入Matcher和CoreMatchers包。

  • import static org.hamcrest.CoreMatchers.*;
  • import static org.hamcrest.Matchers.*;

hamcrest-core.jar和hamcrest-library.jar 下载地址:http://search.maven.org/#search|ga|1|g%3Aorg.hamcrest

Hamcrest官网:http://hamcrest.org/

Hamcrest主页:http://code.google.com/p/hamcrest/wiki/Tutorial

Hamcrest整个包在GitHub的下载地址:https://github.com/hamcrest/JavaHamcrest


其他第三方Matcher如下:

相关文章:

  • 2022-12-23
  • 2021-09-21
  • 2021-07-01
  • 2022-12-23
  • 2021-07-20
  • 2021-05-16
  • 2022-12-23
  • 2021-08-22
猜你喜欢
  • 2021-07-02
  • 2022-02-25
  • 2021-08-09
  • 2021-09-17
  • 2021-08-24
相关资源
相似解决方案