How do I write a unit test to verify async behavior using Spring 4 and annotations?

前端 未结 1 746
礼貌的吻别
礼貌的吻别 2021-01-02 12:04

How do I write a unit test to verify async behavior using Spring 4 and annotations?

Since i\'m used to Spring\'s (old) xml style), it took me some time to figure thi

相关标签:
1条回答
  • 2021-01-02 12:21

    First the service that exposes an async download method:

    @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);
            }
        }
    }
    

    Next the test:

    @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"));
        }
    }
    
    0 讨论(0)
提交回复
热议问题