Search code examples
javatestingjunitejb

How to trigger @Timeout annotation?


I am creating an EJB TimerService mock. Is there a way to manually trigger the call to a method with the @Timeout annotation?


Solution

  • You can create new timer with preferred duration. When you need to call timeout call bellow code segment with duration. Then Framework should call timeout method within given duration from now.

    context.getTimerService().createTimer(duration, "Hello World!");

    Full code

    import javax.annotation.Resource;
    import javax.ejb.SessionContext;
    import javax.ejb.Timer;
    import javax.ejb.Stateless;
    import javax.ejb.Timeout;
    
    @Stateless
    public class TimerSessionBean implements TimerSessionBeanRemote {
    
        @Resource
        private SessionContext context;
    
        public void createTimer(long duration) {
        context.getTimerService().createTimer(duration, "Hello World!");
        }
    
        @Timeout
        public void timeOutHandler(Timer timer){
        System.out.println("timeoutHandler : " + timer.getInfo());        
        timer.cancel();
        }
    }