确认依赖是否存在
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
示例代码
import com.lifetimc.studylab.springboot.service.HelloService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mockito;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.mock.mockito.MockBean;
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.MvcResult;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;
@RunWith(SpringRunner.class)
@SpringBootTest
@AutoConfigureMockMvc
public class StudylabSpringbootApplicationTests {
@MockBean
private HelloService helloService;
@Autowired
private MockMvc mockMvc;
@Test
public void contextLoads() {
Mockito.when(
helloService.getHelloName()
).thenReturn("world");
try {
MvcResult result = mockMvc.perform(
MockMvcRequestBuilders.get("/hello")
.contentType(MediaType.APPLICATION_JSON_UTF8)
).andExpect(MockMvcResultMatchers.status().isOk())
.andExpect(MockMvcResultMatchers.content().string("hello world"))
.andReturn();
} catch (Exception e) {
e.printStackTrace();
}
}
}