springboot 系列教程十:springboot单元测试

单元测试


springboot 支持多种方式的单元测试,方便开发者测试代码,首先需要在 pom 文件中添加 starter

<dependency>
     <groupId>org.springframework.boot</groupId>
     <artifactId>spring-boot-starter-test</artifactId>
     <scope>test</scope>
</dependency>

接着开发一个测试类就可以其实

@RunWith(SpringRunner.class)
@SpringBootTest
public class TestApplication {

    @Autowired
    UserDao dao;

    @Test
    public void test(){
        System.err.println(dao.findAll());
    }
}

测试结果如下图:

由此可见,我们也是可以在测试类里面注入 service、dao 等组件

除了这些常规的测试,springboot 也提供了 MockMvc,可以用来方便的测试 controller 层,我 controller 层代码如下:

@RestController
public class UserController {

    @Autowired
    UserDao dao;

    //查询数据,并且返回给页面显示
    @RequestMapping("/index")
    public String index() {
        System.out.println(dao.findAll());
        return "hello world";
    }

    @RequestMapping("/getUser")
    public String getUser(String id, String name) {
        System.out.println("传入的参数id为:" + id + "---" + name);
        return "ok";
    }
}

接下来我们写一个测试类:

@RunWith(SpringRunner.class)
@SpringBootTest
public class TestController {

    @Autowired
    WebApplicationContext webApplicationContext;
    private MockMvc mvc;

    @Before
    public void init(){
        System.out.println(111);
        mvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
    }

    /**
     * 1、mockMvc.perform执行一个请求。
     * 2、MockMvcRequestBuilders.get("/XXX")构造一个请求。
     * 3、ResultActions.param添加请求传值
     * 4、ResultActions.accept(MediaType.APPLICATION_JSON)设置返回类型
     * 5、ResultActions.andExpect添加执行完成后的断言。
     * 6、ResultActions.andDo添加一个结果处理器,表示要对结果做点什么事情
     *   比如此处使用MockMvcResultHandlers.print()输出整个响应结果信息。
     * 5、ResultActions.andReturn表示执行完成后返回相应的结果。
     */
    @Test
    public void test1() throws Exception{
        mvc.perform(MockMvcRequestBuilders.get("/index")
                .accept(MediaType.APPLICATION_JSON))
                .andExpect(MockMvcResultMatchers.status().isOk())
                .andDo(MockMvcResultHandlers.print())
                .andReturn();
    }

    //带参数测试
    @Test
    public void test2() throws Exception{
        mvc.perform(MockMvcRequestBuilders.get("/getUser")
                .param("id","1001","admin")
                .accept(MediaType.APPLICATION_JSON))
                .andExpect(MockMvcResultMatchers.status().isOk())
                .andDo(MockMvcResultHandlers.print())
                .andReturn();
    }
}

测试结果

完整结果:

MockHttpServletRequest:
      HTTP Method = GET
      Request URI = /getUser
       Parameters = {id=[1001, admin]}
          Headers = [Accept:"application/json"]
             Body = <no character encoding set>
    Session Attrs = {}

Handler:
             Type = com.bdqn.zmj.controller.UserController
           Method = public java.lang.String com.bdqn.zmj.controller.UserController.getUser(java.lang.String,java.lang.String)

Async:
    Async started = false
     Async result = null

Resolved Exception:
             Type = null

ModelAndView:
        View name = null
             View = null
            Model = null

FlashMap:
       Attributes = null

MockHttpServletResponse:
           Status = 200
    Error message = null
          Headers = [Content-Type:"application/json;charset=UTF-8", Content-Length:"2"]
     Content type = application/json;charset=UTF-8
             Body = ok
    Forwarded URL = null
   Redirected URL = null
          Cookies = []

测试类里面的这些测试代码,我相信是个写过基础 web 的人员都能看懂吧!!!!

转载于:https://my.oschina.net/zhoumj/blog/3040139

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值