SpringBoot的controller单元测试

Controller的单元测试

大体代码

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.SpringRunner;
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(SpringRunner.class)
@SpringBootTest(classes = DeltaMainApplication.class)
@WebAppConfiguration
public class DeltaMainApplicationTest {

    @Autowired
    private WebApplicationContext webApplicationContext;

    private MockMvc mvc;


    @Before
    public void setUp() throws Exception{
        mvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
        System.out.println("初始化mock模块");
    }

    @Test
    public void listQueryParams() throws Exception {
        setUp();
        String responseString = mvc.perform(MockMvcRequestBuilders.get("/api/alarm-manage/alarm-desc/query-params").accept(MediaType.APPLICATION_JSON)).andExpect(MockMvcResultMatchers.status().isOk())
                .andDo(MockMvcResultHandlers.print())
                .andReturn().getResponse().getContentAsString();
        System.out.println(responseString);
    }

    @Test
    public void listAlarmRulesDict() throws Exception {
        setUp();
        String responseString = mvc.perform(MockMvcRequestBuilders.get("/api/alarm-manage/alarm-desc/alarm-rules-dict").param("resourceType","ES").accept(MediaType.APPLICATION_JSON)).andExpect(MockMvcResultMatchers.status().isOk())
                .andDo(MockMvcResultHandlers.print())
                .andReturn().getResponse().getContentAsString();
        System.out.println(responseString);
    }

    @Test
    public void overviewResGroup() throws Exception {
        setUp();
        String responseString = mvc.perform(MockMvcRequestBuilders.get("/api/alarm-manage/alarm-desc/overview").param("currentPage","1").param("pageSize","10").param("alarmObject","delta-main").accept(MediaType.APPLICATION_JSON)).andExpect(MockMvcResultMatchers.status().isOk())
                .andDo(MockMvcResultHandlers.print())
                .andReturn().getResponse().getContentAsString();
        System.out.println(responseString);
    }

    @Test
    public void getResGroup() throws Exception {
        setUp();
        String responseString = mvc.perform(MockMvcRequestBuilders.get("/api/alarm-manage/alarm-desc/details/ResGroup@delta-main@1670231864767@XqlFwdWq3yPo1qbCDYNj").accept(MediaType.APPLICATION_JSON)).andExpect(MockMvcResultMatchers.status().isOk())
                .andDo(MockMvcResultHandlers.print())
                .andReturn().getResponse().getContentAsString();
        System.out.println(responseString);
    }

    @Test
    public void delResGroup() throws Exception {
        setUp();
        String responseString = mvc.perform(MockMvcRequestBuilders.delete("/api/alarm-manage/alarm-desc/details/ResGroup@delta-main@1670231864767@XqlFwdWq3yPo1qbCDYNj").accept(MediaType.APPLICATION_JSON)).andExpect(MockMvcResultMatchers.status().isOk())
                .andDo(MockMvcResultHandlers.print())
                .andReturn().getResponse().getContentAsString();
        System.out.println(responseString);
    }


    @Test
    public void updateResGroupState() throws Exception {
        setUp();
        String content = "{\"definition\":\"ResGroup@delta-main@1670231864767@XqlFwdWq3yPo1qbCDYNj\",\"alarmEnable\":false}";
        String responseString = mvc.perform(MockMvcRequestBuilders.post("/api/alarm-manage/alarm-desc/status").content(content).contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON)).andExpect(MockMvcResultMatchers.status().isOk())
                .andDo(MockMvcResultHandlers.print())
                .andReturn().getResponse().getContentAsString();
        System.out.println(responseString);
    }

    @Test
    public void createResGroup() throws Exception {
        setUp();
        String content = "{\"name\":\"京东云ES告警\",\"definition\":\"\",\"description\":\"京云ES告警\",\"alarmEnable\":true,\"resourceType\":\"ES\",\"resourceTypeCnName\":\"京东云ES\",\"alarmObjectType\":\"APPLICATION\",\"alarmObject\":\"fama_api\",\"alarmObjectPlatform\":\"JDOS3_CN\",\"resourcegroupName\":\"\",\"alarmRules\":[{\"ruleKey\":\"\",\"definition\":{\"operator\":[],\"rules\":[{\"name\":\"node1\",\"metricKey\":\"elasticsearch.cluster.status\",\"metricValue\":1,\"operator\":\"GT\",\"windowSize\":10,\"windowRange\":60}]},\"aggregationType\":\"NONE\",\"ruleScope\":\"IP\",\"staticMetricType\":\"esStatus\",\"ruleType\":\"BASIC_BINARY_OPERATION\",\"onlyOnceInterval\":10,\"level\":\"WARNING\",\"alarmdescDefinition\":\"\",\"alarmEnable\":false,\"notifyEnable\":false,\"alarmmessageTemplate\":null}],\"notifyEnable\":true,\"notifyContactGroups\":[\"fama_api\"],\"notifyMethods\":[{\"level\":\"WARNING\",\"methods\":[\"TIMLINE\",\"EMAIL\"]},{\"level\":\"CRITICAL\",\"methods\":[\"TIMLINE\",\"EMAIL\",\"PHONE\"]}]}";
        String responseString = mvc.perform(MockMvcRequestBuilders.post("/api/alarm-manage/alarm-desc/details").content(content).contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON)).andExpect(MockMvcResultMatchers.status().isOk())
                .andDo(MockMvcResultHandlers.print())
                .andReturn().getResponse().getContentAsString();
        System.out.println(responseString);
    }
}

解释说明

@SpringBootTest(classes = DeltaMainApplication.class) 指定程序启动的主类是DeltaMainApplication

@WebAppConfiguration 这个注解是web mvc环境里面的上下文对象,它用来表示ApplicationContext应该是WebApplicationContext,这个WebApplicationContext对象用来创建MockMvc对象

MockMvcBuilders.webAppContextSetup(webApplicationContext).build():是基于webApplicationContext来创建MockMvc对象,用这个来测试controller

MockMvcRequestBuilders.get:创建一个get请求的测试instance,param是传递过去的查询参数,实现浏览器里?a=3这种效果

MockMvcRequestBuilders.post:创建一个post请求的测试instance,content(content).contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON)用来执行post的body里面是字符串类型的content,类型是json,并且接受json类型的返回,content就是压缩后的json字符串,粘到代码里自动转义了

andDo(MockMvcResultHandlers.print()): 打印结果输出

andReturn().getResponse().getContentAsString(): 结果进行复制转储到responseString变量上

accept(MediaType.APPLICATION_JSON)).andExpect(MockMvcResultMatchers.status().isOk() : 接受json类型的数据返回,并且期望返回结果http状态码事200
posted @   SpecialSpeculator  阅读(639)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 记一次.NET内存居高不下排查解决与启示
历史上的今天:
2016-12-08 Python多进程----从入门到放弃
点击右上角即可分享
微信分享提示