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

Viewed 8072

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 this out. So I thought I answer my own question to help others.

2 Answers

If you are using the same example in Java 8 you could also use the CompletableFuture class as follows:

    @Service
    public class DownloadService {
            
            
            @Async
            public CompletableFuture<String> startDownloading(final URL url) throws IOException {

             CompletableFuture<Boolean> future = new CompletableFuture<>();
    
              Executors.newCachedThreadPool().submit(() -> {
                getContentAsString(url);
                future.complete(true);
                return null;
               });
                   return future;
            }
        
           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);
             }
         }
   }

Now 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");

        CompletableFuture<Boolean> content = service.startDownloading(url);

        content.thenRun(() -> {
           assertThat(true, equalTo(content.isDone()));
           assertThat(str, JUnitMatchers.containsString("<html"));
        });

        // wait for completion
        content.get(10, TimeUnit.SECONDS);
        
    }
}

Please that when the time-out is not specified, and anything goes wrong the test will go on "forever" until the CI or you shut it down.

Related