添加依赖 <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> <version>2.5.10</version> </dependency>
模拟端口
虚拟请求测试
@Slf4j @RestController @RequestMapping("/books") public class BookController { @Autowired private IBookService iBookService; @GetMapping("/get/{id}") public R getById(@PathVariable Integer id) throws IOException { return new R(true,iBookService.getById(id)); } @GetMapping public R getAll(){ return new R(true,iBookService.list()); } @PostMapping public R save(@RequestBody Book book) throws IOException { boolean flag = iBookService.save(book); return new R(flag,flag?"添加成功🙂":"添加失败😂"); } @PutMapping public R updateById(@RequestBody Book book){ boolean flag = iBookService.modify(book); return new R(flag,flag?"数据更新成功":"数据更新失败"); } @DeleteMapping("/delete/{integer}") public R deleteById(@PathVariable Integer integer){ boolean flag = iBookService.delete(integer); return new R(flag,flag?"数据删除成功":"数据删除失败"); } @GetMapping("{current}/{pageSize}") public R getByPage(@PathVariable Integer current,@PathVariable Integer pageSize,String name,Book book){ System.out.println("name"+name); System.out.println("book"+book); IPage<Book> ipage=iBookService.getByPage(current,pageSize,book); if(current>ipage.getPages()){ ipage =iBookService.getByPage((int)ipage.getPages(),pageSize,book); } return new R(true,ipage); } }
测试代码
@ContextConfiguration(classes = Application.class)
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
//开启虚拟MVC调用
@AutoConfigureMockMvc
public class WebTest {
@Autowired
private MockMvc mvc;
@Test
//http://localhost/testSpringboot/books
//创建虚拟请求,当前访问books
public void test() throws Exception {
MockHttpServletRequestBuilder mockHttpServletRequestBuilder= MockMvcRequestBuilders.get("/books");
//执行对应的请求
mvc.perform(mockHttpServletRequestBuilder);
}
总结