SpringBoot启用web模拟测试(一)

本文介绍了如何在SpringBoot项目中进行web模拟测试,包括设置模拟端口、创建虚拟请求测试以及编写具体的测试代码,帮助开发者高效地进行单元测试和集成测试。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

添加依赖
<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);
    }

总结

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值