【问题标题】:How to prevent SpringBootTest stop server before async methods finished?如何防止 SpringBootTest 在异步方法完成之前停止服务器?
【发布时间】:2018-01-12 15:53:55
【问题描述】:

我有这样的代码

@RequestMapping(value = "/create", method = RequestMethod.POST)
public Result createModel(DataModel model) {
    CompletableFuture.runAsync(() -> doSomeThing(model));
    return new Result("your request has been recieved successfully");      
}

我尝试像这样编写集成测试

 @RunWith(SpringJUnit4ClassRunner.class)
 @@SpringBootTest(classes = Application.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
 @ActiveProfiles("integration_tests, linux")
 @Transactional
 public class DataServiceTestIT {
    @AutoWired
    private WebApplicationContext wac;

    this.mockMvc = MockMvcBuilders.webAppContextSetup(wac).build();
    this.mockMvc.perform(post('/create')).andExcpect(status().isOk());

    assertEquals(1, JdbcTestUtil.countRowsInTable(jdbcTemplate, "data_model_table));
 }

当后端收到请求时,会立即响应成功消息,真正的作业是异步处理的。 发送响应后,服务器停止,我无法测试 doSomeThing 代码。(我的真实代码更复杂,并且有多个异步部分)

如何防止服务器停止或等待其他方法完成。我的控制器不返回可调用结果。处理完成后,向用户发送通知。我尝试使用 get MvcResult.getAsyncResult() 但我认为它不适合这个。

【问题讨论】:

    标签: asynchronous mockito integration-testing mockmvc spring-boot-test


    【解决方案1】:

    为了等待完成方法,我使用 CompletableFuture 和 doAnswer 以及 callRealMethod。

        @AutoWired
        private WebApplicationContext wac;
        @SpyBean
        private DoSomethingService doSomethingService;
    
        @Test
        public void test() {
        this.mockMvc = MockMvcBuilders.webAppContextSetup(wac).build();
    
        CompletableFuture<String> cf = new CompletableFuture<>();
        doAnswer((invocation) -> {
           invocation.callRealMethod();
           cf.complete("method finished");
           return null;
        }).when(doSomethingService).doSomethingMetod();
        this.mockMvc.perform(post('/create')).andExcpect(status().isOk());
        cf.get(TIME_OUT, TimeUnit.MILLISECONDS);
        assertEquals(1, JdbcTestUtil.countRowsInTable(jdbcTemplate, 
            "data_model_table));
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-06-01
      • 2019-01-04
      • 1970-01-01
      • 1970-01-01
      • 2011-02-21
      • 2017-02-14
      相关资源
      最近更新 更多