如何为 TimerService 调度程序准备基本测试?

How to prepare basic test for TimerService scheduler?

实际上我的代码工作得很好,不幸的是我在尝试为 TimerService 编写集成和单元测试时发现了一些问题,而没有准备 Arquillian 容器。 我的代码,经过简化:

@Startup
@Singleton
public class GeneralDataExecutor {

    @Resource
    private TimerService timerService;

    private Timer timer;

    @PostConstruct
    public void init() {
            timer = timerService.createCalendarTimer(createScheduleExpression(), createTimerConfig());
        }
    }

    @Timeout
    public void execute() {
        //some code
    }
}

任何ideas/tips如何完成事情?

有些框架可以帮助模拟 ejb-container 并帮助 处理异步。

看看 Example of a Timer-Bean

@Stateless
public class StatelessTimerEJB extends CountingBean {

   @PostConstruct
   public void postConstruct() {
       setPostConstructCalled();
   }

   @Timeout
   public void callAsynch()  {
       if (isPostConstructCalled()) {
           logcall();
           return;
       } else {
           logger.error("postconstruct did not work for this instance");
       }
   }
}

以及如何在

中使用 ioc-unit 异步管理器对其进行测试

TestAsynchronousManager

为了测试您的业务功能,测试您的超时方法 ("execute") 并模拟其他所有内容就足够了。

您不需要测试计时器功能,因为这不是您的代码并且已经过大量测试。

示例:

import static org.mockito.Mockito.*;

@ExtendWith(MockitoExtension.class)
class GdeTest{
    @InjectMocks
    GeneralDataExecutor gde = new GeneralDataExecutor();

    @Mock
    TimerService timerService;

     @Test
     void testInitialize() {
     gde.execute();
     //your business assertions here

     //ensure timer initialization
     verify(timerService, times(1)).createCalendarTimer(any(ScheduleExpression.class), 
         any(TimerConfig.class));
     }
}