有人能帮我为下面的serviceImpl类编写JUnit吗
@Component
public class ProcessStatusMasterServiceImpl implements ProcessStatusMasterService {
@Autowired
private ProcessStatusRepository processStatusRepository;
@Autowired
private ApplicationContext applicationContext;
public ProcessAndMacroStatus findProcessMaster(StatusConstant statusConstants) {
ProcessStatusMasterService thisBean = (ProcessStatusMasterService)this.applicationContext.getBean(ProcessStatusMasterService.class);
List<ProcessAndMacroStatus> processStatuses = thisBean.findProcessMasterByCategory(statusConstants.getCategory());
Optional<ProcessAndMacroStatus> processStatusOpt = processStatuses.stream().filter(f -> f.getProcessAndMacroStatusKey().equals(statusConstants.getKey())).findFirst();
if (processStatusOpt.isPresent())
return processStatusOpt.get();
throw new IllegalArgumentException("Unable to find status: " + statusConstants.getKey() + " for category: " + statusConstants.getCategory());
}
@Cacheable({"ProcessStatusMasterCache"})
public List<ProcessAndMacroStatus> findProcessMasterByCategory(String category) {
List<ProcessAndMacroStatus> processStatuses = this.processStatusRepository.findByProcessMacroStatusCategory(category);
return processStatuses;
}
}
下面是我正在尝试的代码,但是我得到的是when(thisBean.findProcessMasterByCategory(StatusConstant.GROUP_STATUS_SUCCESS.getCategory())).thenReturn(processStatuses);
行的NPE
此变量thisbean的原因为空
@RunWith(MockitoJUnitRunner.class)
public class ProcessStatusMasterServiceImplTest {
@Mock
ProcessStatusRepository processStatusRepository;
@Mock
ApplicationContext applicationContext;
@InjectMocks
ProcessStatusMasterServiceImpl processStatusMasterServiceImpl;
@Test
public void findProcessMaster() throws Exception {
ProcessStatusMasterService thisBean = (ProcessStatusMasterService)this.applicationContext.getBean(ProcessStatusMasterService.class);
List<ProcessAndMacroStatus> processStatuses=new ArrayList<ProcessAndMacroStatus>();
when(thisBean.findProcessMasterByCategory(StatusConstant.GROUP_STATUS_SUCCESS.getCategory())).thenReturn(processStatuses);
processStatusMasterServiceImpl.findProcessMaster(StatusConstant.GROUP_STATUS_SUCCESS);
}
}
2条答案
按热度按时间6ss1mwsb1#
我认为你是在试图模仿被测试实体本身的行为,而不是模仿依赖关系。我试着这样模仿它:
ctehm74n2#
请移除您的实际执行程式码中的
thisBean
,改用this.
即可。并修改测试