Controller是这样的:
package com.example.demo;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class HelloController {
@RequestMapping("/hello")
public String index() {
return "Hello World";
}
}
测试类是这样的:
package com.example.demo;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
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.result.MockMvcResultHandlers;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = {DemoApplicationTests.class})// 指定启动类
@AutoConfigureMockMvc
public class DemoApplicationTests {
private MockMvc mvc;
@Before
public void setUp() throws Exception{
mvc = MockMvcBuilders.standaloneSetup(new HelloController()).build();
}
@Test
public void contextLoads() throws Exception{
this.mvc.perform(get("/hello")).andExpect(status().isOk())
.andExpect(content().string("Hello World"))
.andDo(MockMvcResultHandlers.print());
}
}