单元测试

95 阅读1分钟

开启掘金成长之旅!这是我参与「掘金日新计划 · 12 月更文挑战」的第32天,点击查看活动详情

单元测试(unit testing),是指对软件中的最小可测试单元进行检查和验证。对于单元测试中单元的含义,一般来说,要根据实际情况去判定其具体含义,如C语言中单元指一个函数,Java里单元指一个类,图形化的软件中可以指一个窗口或一个菜单等。总的来说,单元就是人为规定的最小的被测功能

1.在pom.xml引入依赖

image.png

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

2.新增com.imooc.springboot.study包并且新增测试文件

image.png

package com.imooc.springboot.study;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

@SpringBootTest
@RunWith(SpringRunner.class)
public class SpringBootStudyTests {
        @Test
        public void method(){
            System.out.println("testExample");
        }
}

代码说明:

  • @SpringBootTest:
  • @RunWith(SpringRunner.class)
  • @Test:表明是单元测试用例方法

3. 执行单元测试用例:

image.png

4.测试异步任务

新增service包并且新建AsyncServiceTests类
image.png 编辑AsyncServiceTests类文件 image.png

@Slf4j
@SpringBootTest
@RunWith(SpringRunner.class)
public class AsyncServiceTests {
    @Autowired
    private AsyncService asyncService;
    @Test
    public void getAsyncProcess() throws InterruptedException {
        asyncService.asyncProcess();
    }
   

}

代码说明:

  • @Autowired private AsyncService asyncService;:引入异步类
  • asyncService.asyncProcess():调用无返回值的异步方法 启动程序: image.png current thread name ImoocAsync_1:返回值是我们在配置文件定义的名称 image.png

5.不引入线程配置文件

注释配置文件注解 image.png 去除Async image.png 重启项目 image.png 可以看到,线程的名称不是我们在配置文件设置ImoocAsync_

6.获取返回值的异步线程

image.png

@Test
public void getAsyncHasReturnProccess() throws InterruptedException, ExecutionException {
    long start = System.currentTimeMillis();
    Future<Integer>  result =  asyncService.asyncProcessHasReturn();
    log.info("get asnc task {}",result.get());

}

代码说明:

  • result.get():返回值使用.get获取 重启项目: image.png 可以看到,返回值是100