• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2007 Mockito contributors
3  * This program is made available under the terms of the MIT License.
4  */
5 package org.mockito.internal.invocation;
6 
7 import org.hamcrest.Matcher;
8 import org.mockito.internal.matchers.ArrayEquals;
9 import org.mockito.internal.matchers.Equals;
10 import org.mockito.internal.util.collections.ArrayUtils;
11 
12 import java.util.ArrayList;
13 import java.util.List;
14 
15 /**
16  * by Szczepan Faber, created at: 3/31/12
17  */
18 public class ArgumentsProcessor {
19     // expands array varArgs that are given by runtime (1, [a, b]) into true
20     // varArgs (1, a, b);
expandVarArgs(final boolean isVarArgs, final Object[] args)21     public static Object[] expandVarArgs(final boolean isVarArgs, final Object[] args) {
22         if (!isVarArgs || new ArrayUtils().isEmpty(args) || args[args.length - 1] != null && !args[args.length - 1].getClass().isArray()) {
23             return args == null ? new Object[0] : args;
24         }
25 
26         final int nonVarArgsCount = args.length - 1;
27         Object[] varArgs;
28         if (args[nonVarArgsCount] == null) {
29             // in case someone deliberately passed null varArg array
30             varArgs = new Object[] { null };
31         } else {
32             varArgs = ArrayEquals.createObjectArray(args[nonVarArgsCount]);
33         }
34         final int varArgsCount = varArgs.length;
35         Object[] newArgs = new Object[nonVarArgsCount + varArgsCount];
36         System.arraycopy(args, 0, newArgs, 0, nonVarArgsCount);
37         System.arraycopy(varArgs, 0, newArgs, nonVarArgsCount, varArgsCount);
38         return newArgs;
39     }
40 
argumentsToMatchers(Object[] arguments)41     public static List<Matcher> argumentsToMatchers(Object[] arguments) {
42         List<Matcher> matchers = new ArrayList<Matcher>(arguments.length);
43         for (Object arg : arguments) {
44             if (arg != null && arg.getClass().isArray()) {
45                 matchers.add(new ArrayEquals(arg));
46             } else {
47                 matchers.add(new Equals(arg));
48             }
49         }
50         return matchers;
51     }
52 }
53