码迷,mamicode.com
首页 > 编程语言 > 详细

springboot-web进阶(四)——单元测试

时间:2018-02-09 22:21:06      阅读:159      评论:0      收藏:0      [点我收藏+]

标签:art   demo   form   amp   nbsp   ice   app   分享图片   targe   

一、概述

  基础知识,参考:https://www.cnblogs.com/ysw-go/p/5447056.html

二、springboot的单元测试

  1.入门测试类

    最重要的不要忘记类上面的依赖,以及类里面方法上的@Test(底层是jUnit)

package com.example.demo;

import com.example.demo.service.GirlService;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

/**
 * GirlService测试类
 *
 * @author zcc ON 2018/2/9
 **/
@RunWith(SpringRunner.class)
@SpringBootTest
public class GirlServiceTest {

    @Autowired
    private GirlService girlService;
    @Test
    public void findOneTest() {
        Assert.assertEquals(new Integer(20), girlService.findOne(4).getAge());
    }
}

    这样,就可以看到相关结果了:

    技术分享图片

    // 为了高大上一点,请不要再使用小白式的sout了,多使用断言.

  2.使用IDEA自动生成测试类

    例如还是测试上面的service里的findOne,则通过在方法上右击->Goto->Test

    技术分享图片

  3.controller的API单元测试

    同样,在方法上右击,Goto->Test,得到测试类

package com.example.demo.controller;

import com.example.demo.SpringbootDemoApplicationTests;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;

import static org.junit.Assert.*;

@AutoConfigureMockMvc
public class GirlControllerTest extends SpringbootDemoApplicationTests {

    @Autowired
    private MockMvc mvc;
    @Test
    public void getList() throws Exception {
        // 测试状态码
        mvc.perform(MockMvcRequestBuilders.get("/girls"))
                .andExpect(MockMvcResultMatchers.status().isOk());
    }

}

    使用单元测试还有一个用处是在打包是会自动跑单元测试,并会给出测试结果,失败时将会报ERROR!

  还有其他测试选项,例如测试.content.string("abc"来测试返回内容),完整的API,参考:这里

springboot-web进阶(四)——单元测试

标签:art   demo   form   amp   nbsp   ice   app   分享图片   targe   

原文地址:https://www.cnblogs.com/jiangbei/p/8436793.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!