1 /*
2  * Copyright (c) 2007 Mockito contributors
3  * This program is made available under the terms of the MIT License.
4  */
5 
6 package org.mockito.internal.invocation;
7 
8 
9 import static org.mockito.internal.exceptions.Reporter.invalidUseOfMatchers;
10 
11 import java.io.Serializable;
12 import java.util.LinkedList;
13 import java.util.List;
14 
15 import org.mockito.ArgumentMatcher;
16 import org.mockito.internal.matchers.LocalizedMatcher;
17 import org.mockito.internal.progress.ArgumentMatcherStorage;
18 import org.mockito.invocation.Invocation;
19 
20 @SuppressWarnings("unchecked")
21 public class MatchersBinder implements Serializable {
22 
bindMatchers(ArgumentMatcherStorage argumentMatcherStorage, Invocation invocation)23     public InvocationMatcher bindMatchers(ArgumentMatcherStorage argumentMatcherStorage, Invocation invocation) {
24         List<LocalizedMatcher> lastMatchers = argumentMatcherStorage.pullLocalizedMatchers();
25         validateMatchers(invocation, lastMatchers);
26 
27         List<ArgumentMatcher> matchers = new LinkedList<ArgumentMatcher>();
28         for (LocalizedMatcher m : lastMatchers) {
29             matchers.add(m.getMatcher());
30         }
31         return new InvocationMatcher(invocation, matchers);
32     }
33 
validateMatchers(Invocation invocation, List<LocalizedMatcher> lastMatchers)34     private void validateMatchers(Invocation invocation, List<LocalizedMatcher> lastMatchers) {
35         if (!lastMatchers.isEmpty()) {
36             int recordedMatchersSize = lastMatchers.size();
37             int expectedMatchersSize = invocation.getArguments().length;
38             if (expectedMatchersSize != recordedMatchersSize) {
39                 throw invalidUseOfMatchers(expectedMatchersSize, lastMatchers);
40             }
41         }
42     }
43 }
44