问题:
我正在为我的春季批量工作方法之一编写单元测试。我使用mockito 来模拟我的批处理作业依赖项。在 jobExecution 发挥作用之前一切都很好。我想要测试的方法调用了 jobExecution 变量,但随后它给了我 NPE (NullPointerException),并且我没有成功用mockito 来模拟它。
我尝试过的事情:
就像问题部分提到的那样,我尝试使用 @Mock 注释来模拟它。
代码:
我的方法需要进行单元测试(currentJobExecution 是给我错误的行):
@Override
public List<Date> getValidDates() {
List<Date> allDates = dateService.findAllFailedDates(getJobName(), false);
List<Date> datesThatCanBeWorkedOn = getAllDatesThatHaveNecessaryDependencies(allDates);
Collection<Date> datesThatCannotBeWorkedOn = CollectionUtils.subtract(allDates, datesThatCanBeWorkedOn);
currentJobExecution.getExecutionContext().put("datesThatCannotBeWorkedOn", datesThatCannotBeWorkedOn);
return datesThatCanBeWorkedOn;
}
我的单元测试尝试测试上面的代码:
@RunWith(SpringJUnit4ClassRunner.class)
public class ValidDateReaderTest extends BaseTest {
@InjectMocks
private ValidDateReader validDateReader;
@Mock
private DateService dateService;
@Mock
private JobExecution currentJobExecution;
@Mock
private JobInstance jobInstance;
@Test
public void getDatesNeededProcessingTest() {
when(jobInstance.getJobName()).thenReturn(BatchNames.VALID_DATE_READER);
when(currentJobExecution.getJobInstance()).thenReturn(jobInstance);
List<Date> allDates = new ArrayList<>();
allDates.add(DateUtils.addDays(new Date(), -5));
allDates.add(DateUtils.addDays(new Date(), -4));
allDates.add(DateUtils.addDays(new Date(), -3));
allDates.add(DateUtils.addDays(new Date(), -2));
allDates.add(DateUtils.addDays(new Date(), -1));
when(dateService.findAllFailedDates(BatchNames.VALID_DATE_READER, false))
.thenReturn(allDates);
assertEquals(1, validDateReader.getValidDates().size());
}
}
预期结果和实际结果:
当我删除这个 currentJobExecution 时
currentJobExecution.getExecutionContext().put("datesThatCannotBeWorkedOn", datesThatCannotBeWorkedOn);
从我想要测试的方法来看,测试成功完成。但我无法删除它,因为它是业务逻辑的一部分。
翻翻过去那场雪
偶然的你
相关分类