使用mock mvc进行模拟接口单元测试

get请求

post请求

文件的请求



import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.context.WebApplicationContext;

import java.util.List;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

/**
 * @decription:
 * @author: zhuangxr002
 * @date 2021/3/2 10:41
 */
@RunWith(SpringJUnit4ClassRunner.class) // SpringJUnit支持,由此引入Spring-Test框架支持!
@SpringBootTest(classes = Application.class)
@Transactional        //单元测试自动回滚
public class NewsEndpointTest {
    // 注入Spring 工厂
    @Autowired
    private WebApplicationContext wac;
    // 伪造mvc环境
    private MockMvc mockMvc;
    private static final String FILE_REQUEST  = "/api/file/";


    @Before
    public void setup(){
        mockMvc = MockMvcBuilders.webAppContextSetup(wac).build();
    }

//get请求
      @Test
    public void newsDetail() throws Exception {
        // 参数
            String result =
                    mockMvc.perform(get(REQUEST+"newsDetail")
                            .contentType(MediaType.APPLICATION_JSON_UTF8)
                            .param("seq", "8"))
                            .andExpect(status().isOk())
                            .andReturn().getResponse().getContentAsString(); //对返回字符串的json内容进行判断
            assertEquals(0, CommonUtil.getReslutCode(result));
    }


//post请求
@Test
    public void list() throws Exception {
        String content = "{\"title\":\"\",\"sourceName\":\"\",\"newsSummary\":\"\",\"bgnDt\":null,\"endDt\":null,\"page\":\"1\",\"limit\":\"5\"}";

        //模拟发送请求
        String result =
                mockMvc.perform(post(REQUEST + "list")
                        .contentType(MediaType.APPLICATION_JSON_UTF8)
                        .content(content))
                        .andExpect(status().isOk())
                        .andReturn().getResponse().getContentAsString(); //对返回字符串的json内容进行判断
        assertEquals(0, CommonUtil.getReslutCode(result));
    }


//file请求
    @Test
    public void uploadFile() throws Exception{
        // 参数
        MockMultipartFile firstFile = new MockMultipartFile("fileupload", "filename.txt", "text/plain", "some xml".getBytes());
        MockMultipartFile secondFile = new MockMultipartFile("fileupload", "other-file-name.data", "text/plain", "some other type".getBytes());

        String result  = mockMvc.perform(MockMvcRequestBuilders.multipart(FILE_REQUEST + "uploadEnclosure")
                .file(firstFile)
                .file(secondFile)
                .param("business", "news")
                .param("entityId","54325235235432543254325432"))
                .andExpect(status().is(200))
                .andReturn().getResponse().getContentAsString();
        assertNotNull(result);

    }
}

 

上面是单元测试案例。 MockMultipartFile的第一个是请求接口的参数名,跟api的接口参数对应fileupload

 

控制器的接口为

/**
     * 共用上传附件等--信息
     */
    @PostMapping("/uploadEnclosure")
    @ResponseBody
    public R uploadEnclosure(@RequestParam(value = "fileupload", required = false) MultipartFile[] fileupload,
                             HttpServletRequest request)  {

        boolean headImgFlag = false;
        String businessType = request.getParameter("business");
        String entityId =  request.getParameter(ENTITY_ID_VARIABLE);
        IamUserInfo userInfo = SecurityContext.getUser().getIamDetail();
        String uid = userInfo.getUid();

        List<Map<String, Object>> resMap ;


        try {
            resMap = newsService.uploadFile(uid, entityId, businessType, fileupload, headImgFlag);

        }catch (DefException e ){
            return R.error(e.getMsg());
        }catch (Exception e1){
            return R.error(e1.getMessage());
        }
    }

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值