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

springboot单元测试controller层

程序员文章站 2022-03-02 18:06:55
...

springboot单元测试controller层。
demo:

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.SpringBootConfiguration;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.test.context.junit4.SpringRunner;
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;

@RunWith(SpringRunner.class)
@SpringBootTest
@SpringBootConfiguration
public class AlarmSearchControllerTests {

    private MockMvc mvc;

    //初始化执行
    @Before
    public void setUp() throws Exception {
        mvc = MockMvcBuilders.standaloneSetup(new AlarmSearchController()).build(); //加入controller测试的对象
    }

    //验证controller是否正常响应并打印返回结果
    @Test
    public void getSearchAlarm() throws Exception {
        //加入类中的url
        mvc.perform(MockMvcRequestBuilders.get("/alarm/searchAlarm").accept(MediaType.APPLICATION_JSON))
                .andExpect(MockMvcResultMatchers.status().isOk())
                .andDo(MockMvcResultHandlers.print())
                .andReturn();
    }
}

run执行,看控制台输出查看输出内容即可。

参考:
http://www.ityouknow.com/springboot/2017/05/09/springboot-deploy.html