使用MockMvc测试带有异步方法所踩的坑及解决办法

来源:互联网 发布:熊猫杀姐姐知乎 编辑:程序博客网 时间:2024/06/13 02:49

        首先说一下怎样使用MockMvc进行单元测试

        第一步是新建一个TestParent类,里面配置好公共的配置,如下所示。

package com.systoon.reportApi;import com.google.gson.Gson;import com.google.gson.GsonBuilder;import com.hazelcast.aws.impl.Constants;import com.systoon.util.ReadProperties;import org.junit.Test;import org.springframework.test.context.ActiveProfiles;import org.springframework.test.context.ContextConfiguration;import org.springframework.test.context.junit4.AbstractJUnit4SpringContextTests;import org.springframework.test.context.web.WebAppConfiguration;@ActiveProfiles("test")@WebAppConfiguration@ContextConfiguration(locations = {//        "classpath*:/applicationContext-disconf.xml",        "classpath*:/applicationContext.xml",        "classpath*:/springmvc.xml"})public class TestParent extends AbstractJUnit4SpringContextTests {    public static final Gson GSON = new GsonBuilder().setDateFormat(Constants.DATE_FORMAT).create();    public static final String INNER_KEY = ReadProperties.getProp("inner_key");    @Test    public void test(){    }}
        第二步:写测试类进行测试
package com.systoon.reportApi;import org.junit.Before;import org.junit.Test;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.http.MediaType;import org.springframework.test.web.servlet.MockMvc;import org.springframework.test.web.servlet.ResultActions;import org.springframework.test.web.servlet.setup.MockMvcBuilders;import org.springframework.web.context.WebApplicationContext;import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;/** * Created  by 600262 on 2017/11/16. */public class ReportPost extends TestParent {    @Autowired    private WebApplicationContext wac;    private MockMvc mockMvc;    @Before    public void setup() {        mockMvc = MockMvcBuilders.webAppContextSetup(wac).build();    }    //更新个人名片举报    @Test    public void testReport20() {        try {            ResultActions perform = mockMvc.perform(post("/inner/updateReport?authSign=C8363025-BDFE-409F-8C08-8DABEBC18CA4")                    .contentType(MediaType.APPLICATION_JSON).content("{\"feedIllegalInput\":{\"closureTime\":1,\"reportFeed\":\"c_1500459436330003\",\"shieldFieldList\":[{\"fieldName\":\"nickname\",\"fieldValue\":\"小幸运\"},{\"fieldId\":510,\"fieldName\":\"洛阳\",\"fieldValue\":\"王世充\"}]},\n" +                            "\"handlePersonId\":374771,\n" +                            "\"handlePersonName\":\"测试者\",\n" +                            "\"handleReason\":\"这名片不合法\",\n" +                            "\"illegalType\":16,\n" +                            "\"reportId\":5105100540948672,\n" +                            "\"type\":1\n" +                            "}"))                    .andExpect(status().isOk())                    .andExpect(jsonPath("$.meta.code").value(0));        } catch (Exception e) {            e.printStackTrace();        }    }     //正常获取到信息    @Test    public void testReport1() {        try {            ResultActions perform = mockMvc.perform(get("/inner/getContentReportInfo?authSign=C8363025-BDFE-409F-8C08-8DABEBC18CA4")                    .param("reportId","1519064188851426"))                    .andExpect(status().isOk())                    .andExpect(jsonPath("$.meta.code").value(0));        } catch (Exception e) {            e.printStackTrace();        }    }      /**     * 更新群聊举报,既发送消息又封禁账户     */    @Test    public void testReport32() {        try {            ResultActions perform = mockMvc.perform(post("/inner/updateReport?authSign=C8363025-BDFE-409F-8C08-8DABEBC18CA4")                    .contentType(MediaType.APPLICATION_JSON).content("{\"groupChatIllegalInput\":{\"messageFeedIdList\":[\"c_1500459436330003\",\"c_1510558939171789\"],\"closureTime\":1,\"closureFeedIdList\":[\"c_1500459436330003\"]},\n" +                            "\"handlePersonId\":374771,\n" +                            "\"handlePersonName\":\"测试者\",\n" +                            "\"handleReason\":\"这群聊涉及广告骚扰\",\n" +                            "\"illegalType\":16,\n" +                            "\"reportId\":1651096104604331,\n" +                            "\"type\":4\n" +                            "}"))                    .andExpect(status().isOk())                    .andExpect(jsonPath("$.meta.code").value(0));        } catch (Exception e) {            e.printStackTrace();        }    }    /**     * 更新内容举报,删除内容,mockMvc在通过域名获取IP和端口号时无法正常执行     */    @Test    public void testReport33() {        try {            ResultActions perform = mockMvc.perform(post("/inner/updateReport?authSign=C8363025-BDFE-409F-8C08-8DABEBC18CA4")                    .contentType(MediaType.APPLICATION_JSON).content("{\"contentIllegalInput\":{\"closureTime\":0,\"deleteContent\":1,\"reportFeed\":\"o_1503976703662186\"},\n" +                            "\"handlePersonId\":374771,\n" +                            "\"handlePersonName\":\"测试者\",\n" +                            "\"handleReason\":\"这内容涉及侮辱诋毁\",\n" +                            "\"illegalType\":17,\n" +                            "\"reportId\":1545109146557203,\n" +                            "\"type\":14\n" +                            "}"))                    .andExpect(status().isOk())                    .andExpect(jsonPath("$.meta.code").value(0));                    } catch (Exception e) {            e.printStackTrace();        }    }}
        在测试第33个用例时总是会莫名其妙的出现子线程挂掉的情况,从网上查了查资料,查阅到的信息如下:

线程不像进程,一个进程中的线程之间是没有父子之分的,都是平级关系。即线程都是一样的, 退出了一个不会影响另外一个。但是所谓的"主线程"main,其入口代码是类似这样的方式调用main的:exit(main(...))。main执行完之后, 会调用exit()。exit() 会让整个进程over终止,那所有线程自然都会退出。
        也就是说,mockMvc.perform方法主线程执行完后,子线程被强制退出了,所以才会出现莫名其妙的问题,解决该问题最简单的办法便是让主线程休息一下,我这里设置休息5秒钟,如下图所示。这样再跑这个用例,就没问题了!



 

阅读全文
0 0
原创粉丝点击