標籤:
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
- 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介面,定製自己想要的匹配符。當開發人員發現自己的某些測試代碼在不同的測試中重複出現,經常被使用,這時就可以自訂匹配符,將這些代碼綁定在一個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