2015-10-14 31 views
2

有沒有辦法建立一個組合Hamcrest匹配器來測試一個對象和這個對象的屬性? - 僞代碼:如何將Hamcrest匹配器應用到被測試的類中?

both(
    instanceof(MultipleFailureException.class) 
).and(
    // pseudo code starts 
    adapt(
    new Adapter<MultipleFailureException, Iterable<Throwable>() 
    { 
     public Iterable<Throwable> getAdapter(MultipleFailureException item) 
     { 
     return item.getFailures(); 
     } 
    }, 
    // pseudo code ends 
    everyItem(instanceOf(IllegalArgumentException.class)) 
) 
) 

背景:我有一個JUnit測試,它對一組動態對象進行迭代。預計每個對象在處理時都會引發異常。收集例外。該試驗預計用含有這些拋出的異常的集合MultipleFailureException結束:

protected final ExpectedException expectation = ExpectedException.none(); 
protected final ErrorCollector collector = new ErrorCollector(); 

@Rule 
public RuleChain exceptionRules = RuleChain.outerRule(expectation).around(collector); 

@Test 
public void testIllegalEnumConstant() 
{ 
    expectation.expect(/* pseudo code from above */); 
    for (Object object : ILLEGAL_OBJECTS) 
    { 
    try 
    { 
     object.processWithThrow(); 
    } 
    catch (Throwable T) 
    { 
     collector.addError(T); 
    } 
    } 
} 

回答

2

我想你可能會尋找hasPropertyhasPropertyWithValue

在這裏看到一個例子:https://theholyjava.wordpress.com/2011/10/15/hasproperty-the-hidden-gem-of-hamcrest-and-assertthat/

另一個我曾與之合作過的東西的實例;在這裏我們檢查我們是否有Quote方法getModels()返回PhoneModel的集合,並且集合中的其中一個項目的屬性makeId等於LG_ID和modelId等於NEXUS_4_ID。

  assertThat(quote.getModels(), 
          hasItem(Matchers.<PhoneModel> hasProperty("makeId", 
              equalTo(LG_ID)))); 
      assertThat(quote.getModels(), 
          hasItem(Matchers.<PhoneModel> hasProperty("modelId", 
              equalTo(NEXUS_4_ID)))); 
    } 

爲了這個工作,hamcrest依靠你採用JavaBean對流。

相關問題