首页 > 其他分享 >springboot测试controller类

springboot测试controller类

时间:2023-02-02 00:33:25浏览次数:58  
标签:web springboot springframework blog controller 测试 org test import

测试代码

package com.demo.controller;

import lombok.extern.slf4j.Slf4j;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
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.result.MockMvcResultHandlers;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;

@RunWith(SpringRunner.class)
@SpringBootTest
@Slf4j
public class HelloControllerTest {
    protected Logger logger = LoggerFactory.getLogger(HelloControllerTest.class);

    private MockMvc mockMvc;

    @Before
    public void setup() throws ClassNotFoundException {
        Class<?> aClass = Class.forName("com.demo.controller.HelloController");
        mockMvc = MockMvcBuilders.standaloneSetup(aClass).build();
    }

    @Test
    public void demo() throws Exception {
        MvcResult mvcResult = mockMvc.perform(MockMvcRequestBuilders.get("/hello"))
                .andExpect(MockMvcResultMatchers.status().isOk())
                .andDo(MockMvcResultHandlers.print())
                .andReturn();

        logger.info(mvcResult.getResponse().getContentAsString());
    }
}

参考链接

https://blog.csdn.net/went_m/article/details/79866411

https://blog.csdn.net/m0_46635265/article/details/123860150?spm=1001.2101.3001.6650.4&utm_medium=distribute.pc_relevant.none-task-blog-2~default~CTRLIST~Rate-4-123860150-blog-79866411.pc_relevant_3mothn_strategy_recovery&depth_1-utm_source=distribute.pc_relevant.none-task-blog-2~default~CTRLIST~Rate-4-123860150-blog-79866411.pc_relevant_3mothn_strategy_recovery&utm_relevant_index=9

标签:web,springboot,springframework,blog,controller,测试,org,test,import
From: https://www.cnblogs.com/csh520mjy/p/17084589.html

相关文章