복붙노트

[SPRING] Spring 4와 주석을 사용하여 비동기 동작을 검증하기위한 단위 테스트를 작성하려면 어떻게해야합니까?

SPRING

Spring 4와 주석을 사용하여 비동기 동작을 검증하기위한 단위 테스트를 작성하려면 어떻게해야합니까?

Spring 4와 주석을 사용하여 비동기 동작을 검증하기위한 단위 테스트를 작성하려면 어떻게해야합니까?

저는 Spring의 (옛날) xml 스타일에 익숙해 졌기 때문에 이것을 이해하는 데 약간 시간이 걸렸습니다. 그래서 나는 다른 사람들을 돕기 위해 내 자신의 질문에 대답했다고 생각했습니다.

해결법

  1. ==============================

    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"));
        }
    }
    
  2. from https://stackoverflow.com/questions/20807232/how-do-i-write-a-unit-test-to-verify-async-behavior-using-spring-4-and-annotatio by cc-by-sa and MIT license