1 16 package org.apache.commons.collections.bag; 17 18 import java.util.Set ; 19 20 import junit.framework.Test; 21 import junit.framework.TestSuite; 22 23 import org.apache.commons.collections.Bag; 24 import org.apache.commons.collections.Predicate; 25 import org.apache.commons.collections.PredicateUtils; 26 27 36 public class TestPredicatedBag extends AbstractTestBag { 37 38 public TestPredicatedBag(String testName) { 39 super(testName); 40 } 41 42 public static Test suite() { 43 return new TestSuite(TestPredicatedBag.class); 44 } 45 46 public static void main(String args[]) { 47 String [] testCaseName = { TestPredicatedBag.class.getName()}; 48 junit.textui.TestRunner.main(testCaseName); 49 } 50 51 53 protected Predicate stringPredicate() { 54 return new Predicate() { 55 public boolean evaluate(Object o) { 56 return o instanceof String ; 57 } 58 }; 59 } 60 61 protected Predicate truePredicate = PredicateUtils.truePredicate(); 62 63 protected Bag decorateBag(HashBag bag, Predicate predicate) { 64 return PredicatedBag.decorate(bag, predicate); 65 } 66 67 public Bag makeBag() { 68 return decorateBag(new HashBag(), truePredicate); 69 } 70 71 protected Bag makeTestBag() { 72 return decorateBag(new HashBag(), stringPredicate()); 73 } 74 75 77 public void testlegalAddRemove() { 78 Bag bag = makeTestBag(); 79 assertEquals(0, bag.size()); 80 Object [] els = new Object [] {"1", "3", "5", "7", "2", "4", "1"}; 81 for (int i = 0; i < els.length; i++) { 82 bag.add(els[i]); 83 assertEquals(i + 1, bag.size()); 84 assertEquals(true, bag.contains(els[i])); 85 } 86 Set set = ((PredicatedBag) bag).uniqueSet(); 87 assertTrue("Unique set contains the first element",set.contains(els[0])); 88 assertEquals(true, bag.remove(els[0])); 89 set = ((PredicatedBag) bag).uniqueSet(); 90 assertTrue("Unique set now does not contain the first element", 91 !set.contains(els[0])); 92 } 93 94 public void testIllegalAdd() { 95 Bag bag = makeTestBag(); 96 Integer i = new Integer (3); 97 try { 98 bag.add(i); 99 fail("Integer should fail string predicate."); 100 } catch (IllegalArgumentException e) { 101 } 103 assertTrue("Collection shouldn't contain illegal element", 104 !bag.contains(i)); 105 } 106 107 public void testIllegalDecorate() { 108 HashBag elements = new HashBag(); 109 elements.add("one"); 110 elements.add("two"); 111 elements.add(new Integer (3)); 112 elements.add("four"); 113 try { 114 Bag bag = decorateBag(elements, stringPredicate()); 115 fail("Bag contains an element that should fail the predicate."); 116 } catch (IllegalArgumentException e) { 117 } 119 try { 120 Bag bag = decorateBag(new HashBag(), null); 121 fail("Expectiing IllegalArgumentException for null predicate."); 122 } catch (IllegalArgumentException e) { 123 } 125 } 126 127 public String getCompatibilityVersion() { 128 return "3.1"; 129 } 130 131 143 } 144 | Popular Tags |