SpringBoot 单元测试

一、引入依赖

 

 

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

 

 

二、测试代码

 

package com.example;

import com.example.pojo.Book;
import com.example.service.BookService;
import org.junit.Before;
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.http.MediaType;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;

import javax.annotation.Resource;
import java.util.List;

@RunWith(SpringRunner.class)//用SpringRunner执行测试用例
@SpringBootTest//这是一个测试类
public class BookControllerTest {

    @Resource
    private BookService bookService;

    @Autowired
    private WebApplicationContext wac;
    private MockMvc mockMvc;
    @Before//伪造一个测试环境,不用启动tomcat,会在每次执行测试用例前执行
    public void setup(){
        mockMvc = MockMvcBuilders.webAppContextSetup(wac).build();
    }

    @Test
    public void findAllTest() throws Exception{
//         List<Book> list = bookService.getAllBooks();
//        System.out.println("=====findAllTest======="+list.toString());
//        for(int i=0;i<list.size();i++){
//            System.out.println(i+"------"+list.get(i).getName());
//        }
        //执行/findAll请求
        mockMvc.perform(MockMvcRequestBuilders.get("/findAll")
                //使用UTF8编码
                .contentType(MediaType.APPLICATION_JSON_UTF8))
                //希望返回状态码是 isOk() 即:200
                .andExpect(MockMvcResultMatchers.status().isOk())
                //希望返回的长度是7
                .andExpect(MockMvcResultMatchers.jsonPath("$.length()").value(7));

    }


}

 

MockMvcResultMatchers.jsonPath  表达式

https://github.com/

https://github.com/json-path/JsonPath

 

 

 

 

 

 

 

 

posted @ 2021-04-12 15:43  残星  阅读(348)  评论(0编辑  收藏  举报