IT数码 购物 网址 头条 软件 日历 阅读 图书馆
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
图片批量下载器
↓批量下载图片,美女图库↓
图片自动播放器
↓图片自动播放器↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁
 
   -> 开发测试 -> @Async注解测试用例附源码 -> 正文阅读

[开发测试]@Async注解测试用例附源码

问题背景

项目开发会用到异步线程去处理一些事情,这个时候使用注解 @Async 非常的简单方便

@Async测试用例

  1. 新建一个 springboot 工程,复制一下pom文件的依赖
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.6.2</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.example</groupId>
    <artifactId>AsyncTest</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>AsyncTest</name>
    <description>AsyncTest</description>
    <properties>
        <java.version>1.8</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <!--scope>test</scope-->
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>compile</scope>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>
  • 可以看到我把 <scope>test</scope> 注释掉了,因为我是在 main.java 文件夹下使用 @SpringTest ,如果不注释掉,那么就不能使用该注解,只能在 test 文件夹下使用,所以 scope 指的就是一个使用的范围
  • 我添加了 junit 依赖,因为测试类的 @Test 注解必须使用这个类
  1. 添加 @EnableAsync 注解在启动类上面
package com.yg.asynctest;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableAsync;

@EnableAsync
@SpringBootApplication
public class AsyncTestApplication {
    public static void main(String[] args) {
        SpringApplication.run(AsyncTestApplication.class, args);
    }
}
  1. 创建异步和同步的方法类
package com.yg.asynctest;

import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.AsyncResult;
import org.springframework.stereotype.Component;
import java.util.concurrent.Future;

@Component
public class Method {
    public int syncMethod() {
        System.out.println("SyncMethod thread: "+Thread.currentThread().getName());
        return 1;
    }
    @Async
    public Future<Integer> asyncMethod() throws InterruptedException {
        System.out.println("AsyncMethod thread: "+Thread.currentThread().getName());
        // 异步线程延时 5s 返回结果
        Thread.sleep(5000);
        return new AsyncResult<>(2);
    }
}
  • 异步方法延时了5s,查看异步调用方法的效果
  1. 创建测试类
package com.yg.asynctest;


import lombok.extern.slf4j.Slf4j;
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 java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;

@Slf4j
@RunWith(SpringRunner.class)
@SpringBootTest
public class AsyncTest {
    @Autowired
    Method method;

    @Test
    public void test() throws ExecutionException, InterruptedException {
        log.info("Sync is {}", method.syncMethod());
        Future<Integer> future = method.asyncMethod();
        log.info("Async is {}", future.get());
    }
}
  • 如果导入 @Test 注解的包错了,会出现如下错误
import org.junit.jupiter.api.Test; // 错误包
java.lang.Exception: No runnable methods

	at org.junit.runners.BlockJUnit4ClassRunner.validateInstanceMethods(BlockJUnit4ClassRunner.java:191)
	at org.junit.runners.BlockJUnit4ClassRunner.collectInitializationErrors(BlockJUnit4ClassRunner.java:128)
	at org.junit.runners.ParentRunner.validate(ParentRunner.java:416)
	at org.junit.runners.ParentRunner.<init>(ParentRunner.java:84)
	at org.junit.runners.BlockJUnit4ClassRunner.<init>(BlockJUnit4ClassRunner.java:65)
	at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.<init>(SpringJUnit4ClassRunner.java:137)
	at org.springframework.test.context.junit4.SpringRunner.<init>(SpringRunner.java:49)
	at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
  • 使用正确的 @Test 包
import org.junit.Test;
  1. 运行 test() 方法,查看日志打印
SyncMethod thread: main
2021-12-24 11:41:40.400  INFO 70184 --- [main] com.yg.asynctest.AsyncTest: Sync is 1
AsyncMethod thread: task-1
2021-12-24 11:41:45.456  INFO 70184 --- [main] com.yg.asynctest.AsyncTest: Async is 2
  • 同步方法使用的是 main 线程,异步方法使用的是 task-1 线程,五秒之后再打印

问题总结

  • 工程中会用到很多异步方法,当然也有使用 Future 线程池的

测试用例源码下载

直接复制文章的代码也是可以的,想少事就直接下载源码:AsyncTest下载链接




作为程序员第七篇文章,每次写一句歌词记录一下,看看人生有几首歌的时间,wahahaha …

Lyric: 我在哑口聆听传说

  开发测试 最新文章
pytest系列——allure之生成测试报告(Wind
某大厂软件测试岗一面笔试题+二面问答题面试
iperf 学习笔记
关于Python中使用selenium八大定位方法
【软件测试】为什么提升不了?8年测试总结再
软件测试复习
PHP笔记-Smarty模板引擎的使用
C++Test使用入门
【Java】单元测试
Net core 3.x 获取客户端地址
上一篇文章      下一篇文章      查看所有文章
加:2021-12-26 22:30:16  更:2021-12-26 22:31:49 
 
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁

360图书馆 购物 三丰科技 阅读网 日历 万年历 2025年2日历 -2025/2/6 7:53:40-

图片自动播放器
↓图片自动播放器↓
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
图片批量下载器
↓批量下载图片,美女图库↓
  网站联系: qq:121756557 email:121756557@qq.com  IT数码