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