2013-02-18 29 views
8

मैं पूर्णांकों (वर्तमान) की एक सूची है और मैं जाँच करने के लिए इस सूची सूची notExpected से उम्मीद सूची से सभी तत्वों और एक भी नहीं तत्व शामिल है कि क्या चाहते हैं, इसलिए कोड लगता है:दुरूपयोग

List<Integer> expected= new ArrayList<Integer>(); 
    expected.add(1); 
    expected.add(2); 

    List<Integer> notExpected = new ArrayList<Integer>(); 
    notExpected.add(3); 
    notExpected.add(4); 

    List<Integer> current = new ArrayList<Integer>(); 
    current.add(1); 
    current.add(2); 


    assertThat(current, not(hasItems(notExpected.toArray(new Integer[expected.size()])))); 

    assertThat(current, (hasItems(expected.toArray(new Integer[expected.size()])))); 

इतनी देर तक बहुत अच्छा। लेकिन जब मैं

current.add(3); 

परीक्षण भी हरा है। क्या मैं हैमरक्रिस्ट मैचर का दुरुपयोग करता हूं? बीटीडब्ल्यू।

for (Integer i : notExpected) 
     assertThat(current, not(hasItem(i))); 

मुझे सही जवाब देता है, लेकिन मैंने सोचा कि मैं आसानी से उस के लिए हैमक्रिस्ट मैचर का उपयोग कर सकता हूं। मैं JUnit 4.11 और hamcrest 1.3

उत्तर

9

hasItems(notExpected...) केवल मेल खाएंगे current उपयोग कर रहा हूँ अगर notExpected से सभी तत्वों current में थे। लाइन

assertThat(current, not(hasItems(notExpected...))); 

साथ तो तुम जोर है कि currentnotExpected से सभी तत्वों शामिल नहीं है।

एक समाधान का दावा करने की है कि currentnotExpected से किसी भी तत्व शामिल नहीं है:

assertThat(current, everyItem(not(isIn(notExpected)))); 

और फिर आप भी सरणी के लिए सूची में कनवर्ट करने की जरूरत नहीं है। ताकि आप hamcrest-library पर निर्भरता जोड़ने की आवश्यकता होगी

assertThat(current, everyItem(not(isOneOf(notExpected...)))); 

ध्यान दें कि इन matchers hamcrest-core में CoreMatchers से नहीं हैं,: इस प्रकार हो सकता है थोड़ा अधिक पठनीय है, लेकिन सरणी के लिए रूपांतरण की आवश्यकता है।

<dependency> 
    <groupId>org.hamcrest</groupId> 
    <artifactId>hamcrest-library</artifactId> 
    <version>1.3</version> 
</dependency>