2014-07-17 30 views
7

我想運行此行代碼:如何實現hamcrest匹配器

assertThat(contextPin.get(), equalTo(pinPage.getPinObjFromUi()));

,但我想打印到日誌翔實

這意味着我可以知道哪些領域不等於。

所以我想到實現一個匹配器。

我用Google搜索,但不能把它寫正確

我的方法不能得到actualexpected對象組合在一起。

這是我的代碼:

我該怎麼寫它乾淨?

public class PinMatcher extends TypeSafeMatcher<Pin> { 

    private Pin actual; 
    private Object item; 

    public PinMatcher(Pin actual) { 
     this.actual = actual; 
    } 

    @Override 
    protected boolean matchesSafely(Pin item) { 
     return false; 
    } 

    @Override 
    public void describeTo(Description description) { 

    } 

//cannot override this way 
    @Override 
    public boolean matches(Object item){ 
     assertThat(actual.title, equalTo(expected.title)); 
return true; 
    } 

//cannot access actual when called like this: 
// assertThat(contextPin.get(), new PinMatcher.pinMatches(pinPage.getPinObjFromUi())); 
    @Override 
    public boolean pinMatches(Object item){ 
     assertThat(actual.title, equalTo(expected.title)); 
return true; 
    } 
} 
+1

請看看源代碼的一些內置的Hamcrest匹配。它們向您展示如何覆蓋matchesSafely和describeTo。 –

回答

1

你的比賽應該在構造函數中接受expected並將其與「實際價值」 item參數傳遞給matchesSafely。您不應該覆蓋matches

這將排隊什麼assertThat預計:

assertThat(actual, matcher-using-expected); 

我認爲,基於字符串匹配器是類型安全的,並會提供一個很好的例子。

4

嘗試更多的東西是這樣的:

package com.mycompany.core; 

import org.hamcrest.Description; 
import org.hamcrest.TypeSafeMatcher; 


public class PinMatcher extends TypeSafeMatcher<Pin> { 

    private Pin actual; 

    public PinMatcher(Pin actual) { 
     this.actual = actual; 
    } 

    @Override 
    protected boolean matchesSafely(Pin item) { 
     return actual.title.equals(item.title); 
    } 

    @Override 
    public void describeTo(Description description) { 
     description.appendText("should match title ").appendText(actual.title); 

    } 
}