hooyantsing's Blog

青铜篇_P14_针对接口编写单元测试代码

字数统计: 403阅读时长: 2 min
2020/07/14

针对接口编写单元测试代码

20年全新-Spring Boot 2.x从青铜到王者之青铜篇-打造精品中的精品-程序员-编程-架构师-SpringBoot

spring-boot-starter-test 包含

  • Junit (JUnit5)
  • Mockito
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    package xyz.hooy.demo.bronze.p14;

    import lombok.extern.slf4j.Slf4j;
    import org.junit.jupiter.api.BeforeAll;
    import org.junit.jupiter.api.Test;
    import org.springframework.http.HttpMethod;
    import org.springframework.test.web.servlet.MockMvc;
    import org.springframework.test.web.servlet.MvcResult;
    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 static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;

    @Slf4j
    public class ArticleRestControllerTest {

    // mock对象
    private static MockMvc mockMvc;

    @BeforeAll
    static void setUP(){
    // 创建mock对象
    mockMvc = MockMvcBuilders.standaloneSetup(new ArticleRestController()).build();
    }

    @Test
    public void saveArticle() throws Exception {
    String article = "{\"id\":1,\"author\":\"Hooy\",\"title\":\"t1\",\"content\":\"从青铜到王者\",\"createTime\":1594733516341}";

    //perform() 执行
    MvcResult mvcResult = mockMvc.perform(
    MockMvcRequestBuilders
    // 测试的URL接口
    .request(HttpMethod.POST , "/rest/articles")
    // 测试的格式类型
    .contentType("application/json")
    // 测试样本
    .content(article)
    //andExpect 期望,类似于断言 andDo 继续做什么 andReturn 返回结果
    ).andExpect(MockMvcResultMatchers.status().isOk())
    .andExpect(MockMvcResultMatchers.jsonPath("$.data.author").value("Hooy"))
    .andExpect(MockMvcResultMatchers.jsonPath("$.data.reader[0].age").value(18))
    .andDo(print())
    .andReturn();

    /* json结构
    {
    "isok" : true ,
    "code" : 200 ,
    "message" : "请求响应成功!"
    "data" : {
    "id" : 1 ,
    "author" : "Hooy" ,
    "title" : "t1" ,
    "content" : "从青铜到王者" ,
    "createTime" : 1594733516341
    "reader" : [
    {
    "name" : "Hooy" ,
    "age" : 18
    } ,
    {
    "name" : "kobe" ,
    "age" : 37
    }
    ]
    }
    }
    */

    //解决控制台输出乱码的问题
    mvcResult.getResponse().setCharacterEncoding("UTF-8");
    log.info(mvcResult.getResponse().getContentAsString());
    }

    }
CATALOG
  1. 1. 针对接口编写单元测试代码