SpringBoot @Test单元测试

一、普通测试

  1. 初步了解:springboot一般使用maven搭建工程,在maven工程中存在test包(虽然测试用例是可以存在于src下,但是规范统一是放在test中),我们的在test包可以同步src下的包结构,针对相应的java类写test用例,在做单元测试这是非常重要的
  2. 一个简单的测试用例,就像main方法一样
    public class UtilTest {
        @Test
        public void currencyTest() throws Exception{
            String uuid = MD5Util.getMd5("测试用例");
    
            System.out.println(uuid);
        }
    }

    注意到这里我们使用了这个注解@Test,由JUnit提供,它回去扫描带有该注解的方法去调用,从而达到相对应的效果

二、SpringBoot调用测试

  1.   我们调用springboot中的controller、service、mapper层时,需要注入它们,需要springboot的相关环境
  2.   测试用例:

@RunWith(SpringRunner.class)
@SpringBootTest(classes = SpringBootCatApplication.class)
public class CatTest {
    @Autowired
    private ElasticDao elasticDao;
    @Autowired
    private testService testService;

    @Test
    public void testEs() throws Exception{
        ResponseEntity responseEntity = elasticDao.saveAndUpdateBulkList(EsIndexEnum.TEST.type,"test","test");
        System.out.println(responseEntity);
    }

    @Test
    public void testTestService() throws Exception{
        ResultEntity ResultEntity = testService.test("1");
        System.out.println(ResultEntity);
    }
}

这里我们添加了两个注解@RunWith@SpringBootTest,可以进入SpringBootTest中查看到这一段代码确认web环境,一般我们将classes指向启动类

SpringBootTest.WebEnvironment webEnvironment() default SpringBootTest.WebEnvironment.MOCK;

三、Junit4单元测试

这个依赖于idea的插件Junit

1、选择要测试的java类
2、按住alt+insert键
3、选择Junit Test
4、选择Junit4
5、生成在test对应包下

测试内容可以选择上述直接调用方法体,也可以是用Junit提供的Mock对象

/**
     * 模拟mvc测试对象
     */
    private MockMvc mockMvc;
 
    /**
     * web项目上下文
     */
    @Autowired
    private WebApplicationContext webApplicationContext;
 
    /**
     * 所有测试方法执行之前执行该方法
     */
    @Before
    public void before() {
        //获取mock对象
        mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
    }

比较测试结果是否符合预期可以使用

Assert.assertEquals("预期结果", "实际结果");
Assert.assertTrue();
Assert.assertNotNull();
Assert.assertNotEquals();
Assert.assertNull();

我们可以使用Jacoco,来获得我们单元测试的分支覆盖率,这里我就不做过多的描述了,有兴趣可以去了解一下

四、pom.xml依赖

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

 

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值