package com.perf.skyhammer; import com.google.gson.Gson; import com.perf.enumBean.Constant; import com.perf.po.DebugPO; import com.perf.task.TestTask; import lombok.extern.slf4j.Slf4j; import org.hamcrest.Matchers; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.http.MediaType; import org.springframework.test.annotation.Rollback; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; import org.springframework.test.web.servlet.result.MockMvcResultMatchers; import org.springframework.transaction.annotation.Transactional; import javax.servlet.http.Cookie; @RunWith(SpringRunner.class) @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) @Rollback @Transactional @AutoConfigureMockMvc @Slf4j public class PlayControllerTest { @Autowired private MockMvc mockMvc; @Autowired private TestTask testTask; @Autowired private Gson gson; @Test public void debugController() throws Exception { DebugPO debugPO = new DebugPO(); debugPO.setCaseId(463); debugPO.setFromLogicName("华东办公一区"); debugPO.setGroupId(-1); debugPO.setGroupType("free"); debugPO.setProjectId(870); debugPO.setRequestIndex("0"); debugPO.setStressTestType(1); this.mockMvc.perform( MockMvcRequestBuilders.post("/play/debug") .contentType(MediaType.APPLICATION_JSON_UTF8) .content(gson.toJson(debugPO)) .header("projectId", 870) .cookie(new Cookie("access_token", Constant.TEST_ACCESS_TOKEN))) .andExpect(MockMvcResultMatchers.status().isOk()) .andExpect(MockMvcResultMatchers.jsonPath("$.success", Matchers.is(true))) .andReturn(); } }
MockMvc模拟HTTP请求进行单元测试样例,但是在进行单元测试的过程中,该用例总会出现子线程挂掉的情况
具体原因如下
-
线程不像进程,一个进程中的线程之间是没有父子之分的,都是平级关系。即线程都是一样的, 退出了一个不会影响另外一个。
-
但是所谓的"主线程"main,其入口代码是类似这样的方式调用main的:exit(main(...))。
-
main执行完之后, 会调用exit()。
-
exit() 会让整个进程over终止,那所有线程自然都会退出。
即当mockMvc.perform方法主线程执行完后,子线程被强制退出,导致上述问题
解决办法:让主线程sleep一段时间,等待子线程执行完成