View Javadoc
1   /*
2    * Copyright (c) 2006 JMockit developers
3    * This file is subject to the terms of the MIT license (see LICENSE.txt).
4    */
5   package mockit.internal.injection;
6   
7   import edu.umd.cs.findbugs.annotations.NonNull;
8   import edu.umd.cs.findbugs.annotations.Nullable;
9   
10  import mockit.Tested;
11  import mockit.internal.state.ParameterNames;
12  import mockit.internal.util.TestMethod;
13  import mockit.internal.util.TypeConversion;
14  
15  import org.checkerframework.checker.index.qual.NonNegative;
16  
17  final class TestedParameter extends TestedObject {
18      @NonNull
19      private final TestMethod testMethod;
20      @NonNegative
21      private final int parameterIndex;
22  
23      TestedParameter(@NonNull InjectionState injectionState, @NonNull TestMethod testMethod,
24              @NonNegative int parameterIndex, @NonNull Tested metadata) {
25          super(injectionState, metadata, testMethod.testClass, ParameterNames.getName(testMethod, parameterIndex),
26                  testMethod.getParameterType(parameterIndex), testMethod.getParameterClass(parameterIndex));
27          this.testMethod = testMethod;
28          this.parameterIndex = parameterIndex;
29      }
30  
31      @Nullable
32      @Override
33      Object getExistingTestedInstanceIfApplicable(@NonNull Object testClassInstance) {
34          Object testedObject = null;
35  
36          if (!createAutomatically) {
37              String providedValue = metadata.value();
38  
39              if (!providedValue.isEmpty()) {
40                  Class<?> parameterClass = testMethod.getParameterClass(parameterIndex);
41                  testedObject = TypeConversion.convertFromString(parameterClass, providedValue);
42  
43                  if (testedObject != null) {
44                      testMethod.setParameterValue(parameterIndex, testedObject);
45                  }
46              }
47  
48              createAutomatically = testedObject == null;
49          }
50  
51          return testedObject;
52      }
53  
54      @Override
55      void setInstance(@NonNull Object testClassInstance, @Nullable Object testedInstance) {
56          testMethod.setParameterValue(parameterIndex, testedInstance);
57      }
58  }