我有一个测试工作,它会产生异常。我想测试异常是否被捕获,并且在通讯期后,该作业再次执行。
在spring example之后,我无法理解。不推荐使用导入。我如何使用mockito证明这一事实?
工作:
public class TestScheduler implements Runnable{
@Override
public void runScheduled(){
LOGGER.info("Doing my tasks...");
throw new RuntimeException("Testing purpose");
}
}
配置:
<bean id="testScheduler" class="com.scheduler.TestScheduler"/>
<bean id="testSchedulerTask" class="org.springframework.scheduling.concurrent.ScheduledExecutorTask">
<property name="delay" value="10"/>
<property name="period" value="60"/>
<property name="runnable" ref="testScheduler"/>
</bean>
提前致谢
答案 0 :(得分:0)
我写了一个简单的测试,如果有人有更好的想法,我会很高兴改进我的代码。
public class TestSchedulerIT extends SpringIntegrationTest {
@Autowired
TestScheduler testScheduler;
@Mock
TestScheduler.TestProperty testString;
@Test
public void testFixedRepeatedExecutionIsSetupAndFiresCorrectly() throws Exception {
int period = 500;
//Set test string
when(testString.getProperty()).thenReturn("Testing");
testScheduler.setTest(testString);
ScheduledExecutorTask task = new ScheduledExecutorTask(testScheduler);
task.setPeriod(period);
task.setDelay(0);
ScheduledExecutorFactoryBean factory = new ScheduledExecutorFactoryBean();
factory.setScheduledExecutorTasks(new ScheduledExecutorTask[]{task});
factory.afterPropertiesSet();
pauseToLetTaskStart(period + 1000);
verify(testString, atLeast(2)).getProperty(); //Verify that the job has been run at least 2 times regardless the exception
factory.destroy();
}
在TestScheduler中我添加了这个属性:
public class TestProperty{
private String property;
TestProperty(String property){
this.property = property;
}
public String getProperty() {
return property;
}
}