【黑马程序员SpringBoot2全套视频教程,springboot零基础到项目实战(spring boot2完整版)】
测试类的web 服务器我们已经启动起来了

如何使用【模拟调用】
先写一个controller
package com.dingjiaxiong.controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* ClassName: BookController
* date: 2022/10/19 20:55
*
* @author DingJiaxiong
*/
@RestController
@RequestMapping("/books")
public class BookController {
@GetMapping
public String getById(){
System.out.println("getById is running ...");
return "SpringBoot";
}
}

先直接启动服务器看看能不能用

OK,没问题
那么在测试类中如何发请求?
编辑测试类
package com.dingjiaxiong;
import org.junit.jupiter.api.Test;
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.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.RequestBuilder;
import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
/**
* ClassName: WebTest
* date: 2022/10/19 20:29
*
* @author DingJiaxiong
*/
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
//1. 开启虚拟MVC调用
@AutoConfigureMockMvc
public class WebTest {
@Test
void testWeb(@Autowired MockMvc mvc) throws Exception {
//创建一个虚拟请求,访问/books
MockHttpServletRequestBuilder builder = MockMvcRequestBuilders.get("/books");
//执行请求
mvc.perform(builder);
}
}
直接运行

OK,就是这样
而且服务器也启动了

这说明咱们写的controller 已经被调用到了【这就实现了一次虚拟调用】
回顾一下

这就是启动web,并把虚拟请求发出去 了