首页 > 解决方案 > 从 SchedulerExecutorService 抛出异常

问题描述

无论如何从SchedulerExecutorService抛出/传播异常?

我可以包装我的 runnable 并在其中包含 errorHandler 但这不会停止我的应用程序。

无论如何我可以从单例访问主线程但是如何强制主线程抛出异常

@Test
    public void executorTest()throws Exception{
        Thread mainThread = Thread.currentThread();
        ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor();
        executorService.scheduleAtFixedRate(() -> {
            try{
                Integer.parseInt("error");
            }catch (Exception e){
                System.err.println("catch error");
                //mainThread.interrupt(); //i want to fail the test , but need a better way
                throw new RuntimeException(e); //this will not affect main thread
            }
        },0,100, TimeUnit.MILLISECONDS);

        Thread.sleep(1000);
        System.out.println("shout not see this statement");
    }

标签: javamultithreadingjunit-jupiter

解决方案


单元测试应该测试一小部分逻辑。如果目标是测试解析功能,推荐的方法是将逻辑提取到新方法(parse())并从调度程序运行中调用 parse() 方法。junit 可以调用 parse() 并测试行为..

相反,如果目的也是验证调度部分,那么您需要调度程序线程和主线程之间的通信模型。有两个不同的错误处理程序实现(生产、单元测试),并将错误处理程序作为依赖项注入。


推荐阅读