java - 从 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");
}
解决方案
单元测试应该测试一小部分逻辑。如果目标是测试解析功能,推荐的方法是将逻辑提取到新方法(parse())并从调度程序运行中调用 parse() 方法。junit 可以调用 parse() 并测试行为..
相反,如果目的也是验证调度部分,那么您需要调度程序线程和主线程之间的通信模型。有两个不同的错误处理程序实现(生产、单元测试),并将错误处理程序作为依赖项注入。
推荐阅读
- c# - 如何发送获取请求然后解析它以获取令牌并再次使用同一会话将带有该令牌的发布请求发送到 C# 中的网站?
- c# - 在 C# 中从 XML 序列化时将空数组添加到 JSON
- javascript - 如果元素不适合 A4 尺寸,请为元素留出空间
- c++ - 读取表示整数的 6 字节、大端二进制字段
- laravel - 我在哪里可以更改 Laravel 中的身份验证错误消息?
- java - 使用 Selenium Java 传递用户名和密码以及用于登录的 url 时出错
- javascript - Angular 5:从组件访问元素内部 html 以获取动态生成的元素
- c# - C# WPF 中的 MVVM 帮助我理解模型和视图模型的关系
- javascript - 为什么我不能通过 Jquery 与 Django 表单元素交互
- java - 用于 rest api 项目的 Spring Boot 战争或 jar