springboot单元测试详解和实战

单元测试是检测代码严密性的最好方式,不仅能减少和预防bug的产生,还能自己二次检查代码或者考虑review必要,如果你还没有养成这个习惯,可要开始关注了。

上节以 springboot快速实战搭建篇 快速入门,本节主要讲述单元测试使用以及多环境配置

maven依赖

pom.xml中引入

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

项目属性文件配置

application.properties配置文件内容如下:

msg=Hello

1.不依赖web模块的单元测试,示例以两种方式读取项目属性文件的值

加入@SpringBootTest注解和@RunWith(SpringRunner.class)注解。

注:1.4.0版本之后这样使用即可

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.core.env.Environment;
import org.springframework.test.context.junit4.SpringRunner;
@SpringBootTest
@RunWith(SpringRunner.class)
public class Test {    
    
    @Value("${msg}")    
    private String msg;    
    
    @Autowired
    private Environment env;      
    
    @Test
    public void testCoreConfig() {
        System.out.println(msg);
    }    
    
    @Test
    public void testCoreConfig2() {
        System.out.println(env.getProperty("msg"));
    }
}

 

 

  • @RunWith(SpringJUnit4ClassRunner.class),这是JUnit的注解,通过这个注解让SpringJUnit4ClassRunner这个类提供Spring测试上下文。

2.使用web模块的单元测试,模拟执行controller等功能

我们以一个简单的Testcontroller为例,get请求访问 路径+"/hello"返回hello字符串。我们想要验证接口是否正常以及返回预期结果判定,则编写以下测试示例

@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringbootDemoApplicationTests {   
   private MockMvc mvc;   
   
   @Before
   public  void setUp() throws Exception {
      //初始化
      mvc = MockMvcBuilders.standaloneSetup(new TestController()).build();
   }   
   
   @Test
   public  void hello() throws Exception {
      String url = "/hello";//访问url
      String expectedResult = "hello";//预期返回结果
      MvcResult mvcResult = mvc.perform(MockMvcRequestBuilders.get(url).accept(MediaType.APPLICATION_JSON))
            .andReturn();      
      //访问返回状态
      int status = mvcResult.getResponse().getStatus();
      //接口返回结果
      String content = mvcResult.getResponse().getContentAsString();
      //打印结果和状态
      //System.out.println(status);
      //System.out.println(content);
      //断言预期结果和状态
      Assert.assertTrue("错误", status == 200);
      Assert.assertFalse("错误", status != 200);
      Assert.assertTrue("数据一致", expectedResult.equals(content));
      Assert.assertFalse("数据不一致", !expectedResult.equals(content));
   }
}

 

更多精彩内容请关注公众号 JAVA葵花宝典

  • 6
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值