这是我要测试的方法:
@Singleton
public class PriorityJobQueueService {
public void registerIndividualJob(String jobCode) throws InterruptedException {
List<PriorityJobMapDTO> priorityJobMapDTOS = CDI.current().select(JobGroupsMasterService.class).get().getJobForCronScheduler(jobCode);
priorityJobMapDTOS = validateStrictJobs(priorityJobMapDTOS);
triggerJob(priorityJobMapDTOS);
}
}
这是我的测试文件的框架结构:
@RunWith(MockitoJUnitRunner.class)
public class PriorityJobQueueServiceTest {
@Before
public void beforeTest() throws Exception {
fixture = new Fixture();
}
@Test
public void registerIndividualJob_SUCCESS() throws InterruptedException {
}
private class Fixture {
@InjectMocks
PriorityJobQueueService priorityJobQueueService;
private Fixture() throws Exception {
MockitoAnnotations.initMocks(this);
}
}
}
现在,我需要做的是模拟CDI.current.select()语句,以便我可以运行测试。
到目前为止,我唯一发现的就是必须使用以下库将其他依赖项添加到我的项目中:
那么还有其他方法可以实现吗?
我将代码更改为可组合的。这就是依赖注入的全部要点:)
@Singleton
public class PriorityJobQueueService {
@Inject
private JobGroupsMasterService jobGroupsMasterService;
public void registerIndividualJob(String jobCode) throws InterruptedException {
List<PriorityJobMapDTO> priorityJobMapDTOS = jobGroupsMasterService.getJobForCronScheduler(jobCode);
priorityJobMapDTOS = validateStrictJobs(priorityJobMapDTOS);
triggerJob(priorityJobMapDTOS);
}
}
现在您的测试将看起来像
@RunWith(MockitoJUnitRunner.class)
class PriorityJobQueueServiceTest {
@Mock
private JobGroupsMasterService jobGroupsMasterService;
@InjectMocks
private PriorityJobQueueService priorityJobQueueService;
@Test
void registerIndividualJob_SUCCESS() throws InterruptedException {
priorityJobQueueService.registerIndividualJob(...);
}
}
欢呼,祝你好运!