I introduce the way to test async method by changing async to sync task executor.
@Service @Slf4j public class TestServiceImpl implements TestService { @Autowired private RestTemplate restTemplate; @Override @Async public void getString() { log.info("start"); restTemplate.getForEntity("http://www.test.com", String.class); } }
We will test this async method as above.
@RunWith(SpringRunner.class) @SpringBootTest @Slf4j public class TestServiceTest { @Configuration @Import(AsyncTestApplication.class) static class ContextConfiguration { @Bean @Primary public Executor executor() { return new SyncTaskExecutor(); } } @Autowired private TestService testService; @MockBean private RestTemplate restTemplate; @Test public void testGetString() { //given given(restTemplate.getForEntity(anyString(), eq(String.class))).willReturn(new ResponseEntity(HttpStatus.OK)); //when testService.getString(); //then verify(restTemplate, times(1)).getForEntity(anyString(), eq(String.class)); } }
By using Configuration annotation, you can set the junit test config.
I will change the asyncExecutor to syncTaskExecutor,so that we could check the internal logic of async method.
2018-03-01 15:54:47.729 INFO 6836 --- [ main] o.b.test.service.impl.TestServiceImpl : start
You can find your test case passed.
You can download whole project from below git url.
https://gitlab.com/shashaka/async-junit-test-project