如何使用Spring 4和注释编写单元测试来验证异步行为?

 sen0226714 发布于 2023-02-07 19:13

如何使用Spring 4和注释编写单元测试来验证异步行为?

因为我已经习惯了Spring的(旧的)xml风格),所以花了一些时间来解决这个问题.所以我想我回答自己的问题来帮助别人.

1 个回答
  • 首先是公开异步下载方法的服务:

    @Service
    public class DownloadService {
        // note: placing this async method in its own dedicated bean was necessary
        //       to circumvent inner bean calls
        @Async
        public Future<String> startDownloading(final URL url) throws IOException {
            return new AsyncResult<String>(getContentAsString(url));
        }
    
        private String getContentAsString(URL url) throws IOException {
            try {
                Thread.sleep(1000);  // To demonstrate the effect of async
                InputStream input = url.openStream();
                return IOUtils.toString(input, StandardCharsets.UTF_8);
            } catch (InterruptedException e) {
                throw new IllegalStateException(e);
            }
        }
    }
    

    接下来的测试:

    @RunWith(SpringJUnit4ClassRunner.class)
    @ContextConfiguration
    public class DownloadServiceTest {
    
        @Configuration
        @EnableAsync
        static class Config {
            @Bean
            public DownloadService downloadService() {
                return new DownloadService();
            }
        }
    
        @Autowired
        private DownloadService service;
    
        @Test
        public void testIndex() throws Exception {
            final URL url = new URL("http://spring.io/blog/2013/01/16/next-stop-spring-framework-4-0");
            Future<String> content = service.startDownloading(url);
            assertThat(false, equalTo(content.isDone()));
            final String str = content.get();
            assertThat(true, equalTo(content.isDone()));
            assertThat(str, JUnitMatchers.containsString("<html"));
        }
    }
    

    2023-02-07 19:14 回答
撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有