1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 package org.apache.commons.functor.core.composite;
18
19 import static org.junit.Assert.assertFalse;
20 import static org.junit.Assert.assertTrue;
21
22 import java.util.LinkedList;
23 import java.util.List;
24
25 import org.apache.commons.functor.BaseFunctorTest;
26 import org.apache.commons.functor.Predicate;
27 import org.apache.commons.functor.Procedure;
28 import org.apache.commons.functor.adapter.BoundPredicate;
29 import org.apache.commons.functor.core.Constant;
30 import org.apache.commons.functor.core.NoOp;
31 import org.apache.commons.functor.core.collection.IsEmpty;
32 import org.junit.Test;
33
34
35
36
37
38 public class TestWhileDoProcedure extends BaseFunctorTest {
39
40
41
42
43 protected Object makeFunctor() {
44 return new WhileDoProcedure(Constant.FALSE, NoOp.INSTANCE);
45 }
46
47
48
49 public class ListRemoveFirstProcedure implements Procedure {
50 protected List<Object> list;
51
52
53 public ListRemoveFirstProcedure(List<Object> list) {
54 this.list=list;
55 }
56
57
58 public void run() {
59 list.remove(0);
60 }
61 }
62
63
64 private List<Object> getList() {
65 List<Object> list=new LinkedList<Object>();
66 list.add("a");
67 list.add("b");
68 list.add("c");
69 list.add("d");
70 return list;
71 }
72
73
74 @Test
75 public void testLoopWithAction() throws Exception {
76 List<Object> list=getList();
77
78 Procedure action=new ListRemoveFirstProcedure(list);
79 Predicate condition=new Not(new BoundPredicate(new IsEmpty<List<Object>>(), list));
80 Procedure procedure=new WhileDoProcedure(condition, action);
81
82 assertTrue("The condition should be true before running the loop", condition.test());
83 assertFalse("The list should not be empty then", list.isEmpty());
84 procedure.run();
85 assertFalse("The condition should be false after running the loop", condition.test());
86 assertTrue("The list should be empty then", list.isEmpty());
87
88 list=getList();
89 action=new ListRemoveFirstProcedure(list);
90 condition=new Predicate() {
91 private int count=2;
92
93 public boolean test() {
94 return count-- > 0;
95 }
96 };
97 procedure=new WhileDoProcedure(condition, action);
98 procedure.run();
99 assertFalse("The list should not contain \"a\" anymore", list.contains("a"));
100 assertFalse("The list should not contain \"b\" anymore", list.contains("b"));
101 assertTrue("The list should still contain \"c\"", list.contains("c"));
102 assertTrue("The list should still contain \"d\"", list.contains("d"));
103 }
104
105 @Test
106 public void testLoopForNothing() {
107 List<Object> list=getList();
108 Procedure action=new ListRemoveFirstProcedure(list);
109 Procedure procedure=new WhileDoProcedure(Constant.FALSE, action);
110 assertTrue("The list should contain 4 elements before runnning the loop", list.size()==4);
111 procedure.run();
112 assertTrue("The list should contain 4 elements after runnning the loop", list.size()==4);
113 }
114 }
115