springboot测试controller类
测试代码
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());
}
}
参考链接
本文来自博客园,作者:土木转行的人才,转载请注明原文链接