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

spring boot controller 单元测试

程序员文章站 2022-04-29 16:44:25
...
package net.cqfishing.cloud_m_system.controller.api.banner;

import net.cqfishing.cloud_m_system.CloudMSystemApplication;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.test.context.ContextConfiguration;
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.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.result.MockMvcResultHandlers;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;

@RunWith(SpringJUnit4ClassRunner.class)//Spring对Junit4的支持
@SpringBootTest(classes = CloudMSystemApplication.class)
@ContextConfiguration(classes = {WebApplicationContext.class})
@WebAppConfiguration(value = "src/main/java")//开启Web应用的配置,用于模拟ServletContext
public class BannerInfoApiControllerTest {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    private MockMvc mvc;//用于模拟调用Controller的接口发起请求,

    @Autowired
    private WebApplicationContext webApplicationContext;

    @Autowired
    private BannerInfoApiController bannerInfoApiController;

    @Before
    public void setUp() throws Exception {
        mvc = MockMvcBuilders.standaloneSetup(bannerInfoApiController).build();
    }

    @Test
    public void getIndexBannerList() throws Exception {

        String url = "/api/banner/getIndexBannerList";//测试成功;
        mvc.perform(
                MockMvcRequestBuilders.post(url)
                        .param("page", "1")
                        .param("pageSize", "10")
                        .accept(MediaType.APPLICATION_JSON))

                .andDo(MockMvcResultHandlers.print())
                .andExpect(MockMvcResultMatchers.status().isOk())
                .andExpect(MockMvcResultMatchers.content().string("success"))//断言结果字符串
                .andDo(MockMvcResultHandlers.print());
    }
}