问题:我正在为我的春季批量工作方法之一编写单元测试。我使用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);从我想要测试的方法来看,测试成功完成。但我无法删除它,因为它是业务逻辑的一部分。
2 回答
翻翻过去那场雪
TA贡献2065条经验 获得超13个赞
看来是currentJobExecution.getExecutionContext()
要回归了null
。你可能也想嘲笑它:
when(currentJobExecution.getExecutionContext()).thenReturn(new ExecutionContext());
偶然的你
TA贡献1841条经验 获得超3个赞
在测试逻辑之前调用它(例如在@Before
方法中):
MockitoAnnotations.initMocks(this);
@RunWith(MockitoJUnitRunner.class)
或者,如果您不需要 Spring 上下文,则更改您的单元测试运行程序。
添加回答
举报
0/150
提交
取消