[SPRING] Spring 4와 주석을 사용하여 비동기 동작을 검증하기위한 단위 테스트를 작성하려면 어떻게해야합니까?
SPRINGSpring 4와 주석을 사용하여 비동기 동작을 검증하기위한 단위 테스트를 작성하려면 어떻게해야합니까?
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")); } }
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
'SPRING' 카테고리의 다른 글
[SPRING] 초기 뷰 호출에서 Angular JS의 Spring MVC에서 데이터 가져 오기 (0) | 2019.03.30 |
---|---|
[SPRING] Spring Boot, @Configurable을 사용하여 관리되지 않는 클래스에 @Autowire로드 및 시간 짜기 (0) | 2019.03.29 |
[SPRING] 봄 필터 예외 처리 (0) | 2019.03.29 |
[SPRING] AOP의 Advisor와 Aspect의 차이점은 무엇입니까? (0) | 2019.03.29 |
[SPRING] Hibernate EntityManager, 그것은 싱글 톤으로 사용되어야 하는가? (0) | 2019.03.29 |