Results.java revision 47d431f63a66505a645f282416659a9758a91f1c
1/*
2 * Copyright 2001-2009 OFFIS, Tammo Freese
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *     http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16package org.easymock.internal;
17
18import java.io.Serializable;
19import java.util.ArrayList;
20import java.util.LinkedList;
21import java.util.List;
22
23public class Results implements Serializable {
24
25    private static final long serialVersionUID = -2722051869610289637L;
26
27    private int callCount;
28
29    private final LinkedList<Range> ranges = new LinkedList<Range>();
30
31    private final List<Result> results = new ArrayList<Result>();
32
33    public void add(Result result, Range range) {
34        if (!ranges.isEmpty()) {
35            Range lastRange = ranges.getLast();
36            if (!lastRange.hasFixedCount())
37                throw new RuntimeExceptionWrapper(
38                        new IllegalStateException(
39                                "last method called on mock already has a non-fixed count set."));
40        }
41        ranges.add(range);
42        results.add(result);
43    }
44
45    public Result next() {
46        int currentPosition = 0;
47        for (int i = 0; i < ranges.size(); i++) {
48            Range interval = ranges.get(i);
49            if (interval.hasOpenCount()) {
50                callCount += 1;
51                return results.get(i);
52            }
53            currentPosition += interval.getMaximum();
54            if (currentPosition > callCount) {
55                callCount += 1;
56                return results.get(i);
57            }
58        }
59        return null;
60    }
61
62    public boolean hasValidCallCount() {
63        return getMainInterval().contains(getCallCount());
64    }
65
66    @Override
67    public String toString() {
68        return getMainInterval().expectedCount();
69    }
70
71    private Range getMainInterval() {
72        int min = 0, max = 0;
73
74        for (Range interval : ranges) {
75            min += interval.getMinimum();
76            if (interval.hasOpenCount() || max == Integer.MAX_VALUE) {
77                max = Integer.MAX_VALUE;
78            } else {
79                max += interval.getMaximum();
80            }
81        }
82
83        return new Range(min, max);
84    }
85
86    public int getCallCount() {
87        return callCount;
88    }
89}
90