Springboot单元测试样例以及爬坑

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请求进行单元测试样例,但是在进行单元测试的过程中,该用例总会出现子线程挂掉的情况

具体原因如下

  1. 线程不像进程,一个进程中的线程之间是没有父子之分的,都是平级关系。即线程都是一样的, 退出了一个不会影响另外一个。

  2. 但是所谓的"主线程"main,其入口代码是类似这样的方式调用main的:exit(main(...))。

  3. main执行完之后, 会调用exit()。

  4. exit() 会让整个进程over终止,那所有线程自然都会退出。

即当mockMvc.perform方法主线程执行完后,子线程被强制退出,导致上述问题

解决办法:让主线程sleep一段时间,等待子线程执行完成

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值