Spring boot 单元测试

       本随笔记录使用Spring Boot进行单元测试,主要是Service和API(Controller)进行单元测试。

       一、Service单元测试

       选择要测试的service类的方法,使用idea自动创建测试类,步骤如下。(注,我用的是idea自动创建,也可以自己手动创建)

       自动创建测试类之后目录如下图:

       测试类StudentServiceTest.java代码如下:

复制代码
package *; //自己定义路径

import *.Student; //自己定义路径
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;
import static org.junit.Assert.*;

@RunWith(SpringRunner.class)
@SpringBootTest
public class StudentServiceTest {
    @Autowired
    private StudentService studentService;

    @Test
    public void findOne() throws Exception {
        Student student = studentService.findOne(1);
        Assert.assertEquals(new Integer(16), student.getAge());
    }
}
复制代码

       二、API(Controller)单元测试

      根据上面的步骤创建单元测试类StudentControllerTest.java,代码如下:

复制代码
package *; //自己定义路径

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.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;
import static org.junit.Assert.*;

@RunWith(SpringRunner.class)
@SpringBootTest
@AutoConfigureMockMvc
public class StudentControllerTest {
    @Autowired
    private MockMvc mvc;

    @Test
    public void getStudentList() throws Exception {
        mvc.perform(MockMvcRequestBuilders.get("/students"))
                .andExpect(MockMvcResultMatchers.status().isOk());
        //.andExpect(MockMvcResultMatchers.content().string("365"));  //测试接口返回内容
    }

}
复制代码

       三、service和API(Controller)类和方法

       StudentController.java代码如下:

复制代码
package *; //自己定义路径

import *.StudentRepository; //自己定义路径
import *.Student; //自己定义路径
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import javax.validation.Valid;
import java.util.List;

@RestController
public class StudentController {
    @Autowired
    private StudentRepository studentRepository;

    /**
     * 查询学生列表
     * @return
     */
    @GetMapping(value = "/students")
    public List<Student> getStudentList(){
        return studentRepository.findAll();
    }
}
复制代码

       StudentService.java代码如下:

复制代码
package *; //自己定义路径

import *.StudentRepository; //自己定义路径
import *.Student; //自己定义路径
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class StudentService {
    @Autowired
    private StudentRepository studentRepository;

    /**
     * 根据ID查询学生
     * @param id
     * @return
     */
    public Student findOne(Integer id){
        return studentRepository.findOne( id);
    }
}
复制代码

 

捕获输出
使用 OutputCapture 来捕获指定方法开始执行以后的所有输出,包括System.out输出和Log日志。
OutputCapture 需要使用@Rule注解,并且实例化的对象需要使用public修饰,如下代码:

package com.wen.test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.hamcrest.Matchers;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.rule.OutputCapture;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import com.wen.boot.App;

@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes=App.class)
@WebAppConfiguration
public class HelloControllerTest {
    private static final Logger logger = LoggerFactory.getLogger(HelloControllerTest.class);
    private RestTemplate template = new RestTemplate();
    @Test
    public void test3(){
        try {
              String url = "http://localhost:8082/hello/test.do";
                MultiValueMap<String, Object> map = new LinkedMultiValueMap<String, Object>(); 
                map.add("name", "Tom");  
                String result = template.postForObject(url, map, String.class);
                System.out.println(result);

        }catch (Exception e) {
            // TODO: handle exception
        e.printStackTrace();
        }

    }

    @Rule
    // 这里注意,使用@Rule注解必须要用public
    public OutputCapture capture = new OutputCapture();
    @Test
    public void test4(){
        System.out.println("HelloWorld");
        logger.info("logo日志也会被capture捕获测试输出");
    }

}

参考:
https://www.jianshu.com/p/8308fd12d0cb
https://blog.csdn.net/weixin_42033269/article/details/80035805
https://www.jianshu.com/p/ef9223d5b963

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值