• 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.stubbing.answers;
6 
7 import java.lang.reflect.Array;
8 
9 import org.mockito.creation.instance.Instantiator;
10 import org.mockito.internal.configuration.plugins.Plugins;
11 import org.mockito.internal.stubbing.defaultanswers.ReturnsEmptyValues;
12 import org.mockito.internal.util.reflection.LenientCopyTool;
13 import org.mockito.invocation.InvocationOnMock;
14 import org.mockito.stubbing.Answer;
15 
16 // TODO this needs documentation and further analysis - what if someone changes the answer?
17 // we might think about implementing it straight on MockSettings
18 public class ClonesArguments implements Answer<Object> {
19     @Override
answer(InvocationOnMock invocation)20     public Object answer(InvocationOnMock invocation) throws Throwable {
21         Object[] arguments = invocation.getArguments();
22         for (int i = 0; i < arguments.length; i++) {
23             Object from = arguments[i];
24             if (from != null) {
25                 if (from.getClass().isArray()) {
26                     int len = Array.getLength(from);
27                     Object newInstance = Array.newInstance(from.getClass().getComponentType(), len);
28                     for (int j = 0; j < len; ++j) {
29                         Array.set(newInstance, j, Array.get(from, j));
30                     }
31                     arguments[i] = newInstance;
32                 } else {
33                     Instantiator instantiator =
34                             Plugins.getInstantiatorProvider().getInstantiator(null);
35                     Object newInstance = instantiator.newInstance(from.getClass());
36                     new LenientCopyTool().copyToRealObject(from, newInstance);
37                     arguments[i] = newInstance;
38                 }
39             }
40         }
41         return new ReturnsEmptyValues().answer(invocation);
42     }
43 }
44