I am trying to mock dependencies inside my Spy object but mockito is not able to inject the mock objects as I am getting NullPointerException inside the Spy object.
My code is as follows:
@Component()
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class Target implements Target<InputPojo> {
private final TargetHelper<InputPojo> inputHelper;
@Override
public List<ProcessedPojo> testMethod(List<InputPojo> inputs) throws someException {
inputHelper.process(inputs);
// ...further processing ...
return processedList;
}
}
@Component()
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class MyTargetHelper implements TargetHelper<InputPojo> {
private final Map<SomeEnum, Double> someMap;
private final AlertService alertService;
private final DatabaseService databaseService;
@Override
public void process(List<InputPojo> inputs) throws SomeException {
try {
for (InputPojo i : inputs) {
furtherProcess(databaseService.fetchForId(i.getId())); // Null pointer exception
}
} catch (SomeOtherException e) {
alertService.raiseAlert("database error");
throw(new SomeException());
}
}
}
@ExtendWith(MockitoExtension.class)
class TargetTest {
@InjectMocks
Target target;
@Mock
DatabaseService databaseService;
@Mock
AlertService alertService;
@Spy
Map<SomeEnum, Double> someMap = new EnumMap<>(SomeEnum.class);
@Spy
@InjectMocks
MyTargetHelper inputHelper = new MyTargetHelper(someMap, alertService, databaseService);
static final List<InputPojo> inputs;
static {
// add values to inputs and someMap
}
@Test
@SneakyThrows
void testTarget() {
when(databaseService.fetchForId(anyString())).thenReturn("fetch success");
target.testMethod(inputs);
}
}
I have tried every other related question but none of them could solve my issue. I also tried changing
private final TargetHelper<InputPojo> inputHelper;
to
private final MyTargetHelper inputHelper;
but it didn't help. I have tried
- Mockito Inject mock into Spy object (except the Accepted Answer as I am already Autowiring dependencies instead of @Inject)
I need to run Helper as part of my unit test in order to properly verify results of the TargetMethod, hence I want to Spy the method, however, I will need to mock the database service and alert service in order to make HelperMethod work properly.