zoukankan      html  css  js  c++  java
  • 九、测试service和API(单元测试)

    1、测试service在test目录的下新建被测试的方法类同名包结构;编写测试类方法(或者idea在被测试的方法上右键 Goto 勾选被测试的方法自动添加简单代码结构
    package com.du.service;
    
    import com.du.domain.Gril;
    import com.du.service.GrilService;
    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;
    
    @RunWith(SpringRunner.class)//表示项目将要在测试环境下运行
    @SpringBootTest//将启功整个spring的工程
    public class GrilServiceTest {
        @Autowired
        private GrilService grilService;
    
        @Test
        public void findOneTest() {
            Gril gril = grilService.findone(16);
            Assert.assertEquals(new Integer(23), gril.getAge());
        }
    }

    2、对API接口的测试,同样的是在同包名目录下进行编写测试代码

    package com.du.controller;
    
    import org.junit.Test;
    import org.junit.runner.RunWith;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
    import org.springframework.boot.test.context.SpringBootTest;
    import org.springframework.test.context.junit4.SpringRunner;
    import org.springframework.test.web.servlet.MockMvc;
    import org.springframework.test.web.servlet.request.MockMultipartHttpServletRequestBuilder;
    import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
    import org.springframework.test.web.servlet.result.MockMvcResultMatchers;
    
    import static org.junit.Assert.*;
    
    @RunWith(SpringRunner.class)
    @SpringBootTest
    @AutoConfigureMockMvc
    public class GrilControllerTest {
        @Autowired
        private MockMvc mvc;
    
        @Test
        public void girlList() throws Exception{
            mvc.perform(MockMvcRequestBuilders.get("/grils"))//对接口的请求
                    .andExpect(MockMvcResultMatchers.status().isOk())//isOK返回码为200
                    .andExpect(MockMvcResultMatchers.content().string("abv"))//返回内容的判断
            ;
        }
    }
    1、运行所有的测试用例在项目上右键选择 Run all test或者进行打包项目执行mvn clean package 会自动执行测试用例
    2、使用maven命令打包,如果为idea环境,右键项目选择open in terminal进入命令行界面打包
    打包的时候跳过单元测试在命令行输入如下命令 
    mvn clean package -Dmaven.test.skip=true
  • 相关阅读:
    过往总结
    查找光标处的标识符
    【转】Linux 内核开发 Eclipse内核开发环境搭建
    【转】Writing linux kernel code in Eclipse
    【转】 Linux内核升级指南
    [转]Ubuntu 11.04 安装后要做的20件事情
    【转】vim 替换操作大全
    【转】移动硬盘安装ubuntu
    重置 Winsock 目录
    【转】让Firefox像vim一样操作
  • 原文地址:https://www.cnblogs.com/404code/p/10569170.html
Copyright © 2011-2022 走看看