欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Spring Boot Controller层单元测试

程序员文章站 2022-04-26 09:17:33
...
package com.thrall.dongrj.controller;


import com.alibaba.fastjson.JSON;
import com.thrall.Application;
import com.thrall.business.vo.QuoteGroupVO;
import com.thrall.common.utils.Constants;
import com.thrall.common.utils.page.PageParam;
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.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;

import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;

@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = Application.class)
@WebAppConfiguration
public class ControllerTest {

    @Autowired
    private WebApplicationContext wac;

    private MockMvc mockMvc;

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

    @Test
    public void test01() throws Exception {
        MvcResult result = mockMvc.perform(MockMvcRequestBuilders.get("/customer/{id}", 123)).andDo(print()).andReturn();
        System.out.println(result.getResponse().getContentAsString());
    }

    /**
     * 添加报价
     */
    @Test
    public void test02() throws Exception {
        PageParam<QuoteGroupVO> pageParam = new PageParam<>();
        pageParam.setCurrentPage(1);
        pageParam.setPageSize(20);
        QuoteGroupVO quoteGroup = new QuoteGroupVO();
        quoteGroup.setStatus(1);
        pageParam.setModel(quoteGroup);
        String requestBody = JSON.toJSONString(pageParam);
        System.out.println(requestBody);
        MvcResult result = mockMvc.perform(MockMvcRequestBuilders.get("/quotegroup").
                contentType(MediaType.APPLICATION_JSON).content(requestBody))
                .andDo(print()).andReturn();
        System.out.println(result);
    }
}

转载于:https://my.oschina.net/famiover/blog/828441