您的位置:首页 > 编程语言 > Java开发

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

2018-02-09 20:52 495 查看

一、概述

  基础知识,参考: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,参考:这里
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: