Matchers and assertthat

來源:互聯網
上載者:User

標籤:

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.易讀的失敗提示資訊。

[java] view plaincopy
  1. import static org.junit.Assert.*;  
  2. import static org.hamcrest.CoreMatchers.*;  
  3. import org.junit.Test;  
  4.   
  5. public class AssertThat {  
  6.     @Test  
  7.     public void testMessage(){  
  8.         String s=new String("hello world");  
  9.           
  10.         assertTrue(s.contains("i")||s.contains("happy"));  
  11.         // failure message:   
  12.         // java.lang.AssertionError:  
  13.         assertThat(s,anyOf(containsString("i"),containsString("happy")));  
  14.         //failure message:  
  15.         //java.lang.AssertionError:   
  16.         //Expected: (a string containing "i" or a string containing "happy")  
  17.         //  but: was "hello world"  
  18.     }  
  19. }  

4.開發人員可以通過實現Matcher介面,定製自己想要的匹配符。當開發人員發現自己的某些測試代碼在不同的測試中重複出現,經常被使用,這時就可以自訂匹配符,將這些代碼綁定在一個Assert 陳述式中。

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如下:

    • Excel spreadsheet matchers
    • JSON matchers
    • XML/XPath matchers

Matchers and assertthat

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.