junit自定义ArgumentsSource以自定义ParameterizedTest参数加载方式

junit提供了ArgumentsSource注解以便于用户自定义ParameterizedTestt参数加载方式

直接上代码

核心代码

kotlin 复制代码
import cn.hutool.core.io.resource.ResourceUtil
import org.junit.jupiter.api.extension.ExtensionContext
import org.junit.jupiter.params.ParameterizedTest
import org.junit.jupiter.params.provider.AnnotationBasedArgumentsProvider
import org.junit.jupiter.params.provider.Arguments
import org.junit.jupiter.params.provider.ArgumentsSource
import org.junit.jupiter.params.support.ParameterDeclarations
import java.nio.charset.StandardCharsets
import java.util.stream.Stream


@Target(AnnotationTarget.FUNCTION) //简单的只允许放在测试方法上
@MustBeDocumented
@Retention
@ParameterizedTest //这样就不需在用例上加上这个注解了
@ArgumentsSource(YamlAnnotationBasedArgumentsProvider::class)
annotation class MyYamlSource(
    val value: Array<String>
)
class YamlAnnotationBasedArgumentsProvider: AnnotationBasedArgumentsProvider<MyYamlSource>() {
    override fun provideArguments(
        parameters: ParameterDeclarations,
        context: ExtensionContext,
        source: MyYamlSource
    ): Stream<out Arguments?> {
        //读取每一个配置
        return source.value.map {
            var s = it
            //当配置以后缀结尾则读取文件,否则配置文本就是yaml
            if(s.endsWith(".yaml")||s.endsWith(".yml")) {
                s = ResourceUtil.readStr(s, StandardCharsets.UTF_8)
            }
            val yaml = MyUtil.YAML.load<LinkedHashMap<String, Any>>(s)
            val args = parameters.all.map {
                var pv = yaml.getOrDefault(it.parameterIndex.toString(),null)
                if (pv!=null && !pv::class.java.isAssignableFrom(it.parameterType)){
                    pv = MyUtil.JSON_MAPPER.convertValue(pv,it.parameterType)
                }
                return@map pv
            }.toTypedArray()
            //包装后返回流
            return@map Arguments.of(*args)
        }.stream()
    }
}

所需的工具类

kotlin 复制代码
import org.yaml.snakeyaml.LoaderOptions
import org.yaml.snakeyaml.Yaml
import org.yaml.snakeyaml.constructor.Constructor
import org.yaml.snakeyaml.inspector.TagInspector
import tools.jackson.core.json.JsonReadFeature
import tools.jackson.databind.json.JsonMapper
import tools.jackson.databind.jsontype.BasicPolymorphicTypeValidator
import java.text.SimpleDateFormat
import java.util.*

object MyUtil {
    @JvmField
    val JSON_PTV: BasicPolymorphicTypeValidator = BasicPolymorphicTypeValidator.builder()
        .allowIfSubType("local.demo_sb4")
        .build()
    @JvmField
    val JSON_MAPPER: JsonMapper = JsonMapper.builder()
        .polymorphicTypeValidator(JSON_PTV)
        .apply {
            defaultDateFormat(SimpleDateFormat("yyyy-MM-dd HH:mm:ss"))
            defaultLocale(Locale.CHINA)
            defaultTimeZone(TimeZone.getTimeZone("GMT+8"))
        }
        .apply {
            for (feature in JsonReadFeature.entries) {
                if(feature.name.startsWith("ALLOW"))
                    configure(feature, true)
            }
        }
        .build()
    val YAML: Yaml = Yaml(Constructor(LoaderOptions().also {
        it.tagInspector = TagInspector { true }
    }))
}

运行测试

java 复制代码
public class MyTest {
    public static class Obj {
        public String name;
    }
    @MyYamlSource({"test1.yml"})
    public void test1(Obj o){
        System.out.println(o.name);
    }
}
/*
输出:
> Task :testClasses
测试
> Task :test
*/
相关推荐
DJ斯特拉4 天前
Redis使用lua脚本
junit·单元测试·lua
2301_771717214 天前
idea中springboot中使用junit测试报错的解决方案
spring boot·junit·intellij-idea
Java成神之路-5 天前
Spring 整合 MyBatis 全流程详解(附 Junit 单元测试实战)(Spring系列6)
spring·junit·mybatis
難釋懷6 天前
OpenResty封装Redis工具
redis·junit·openresty
希望永不加班8 天前
SpringBoot 接口测试:Postman 与 JUnit 5 实战
java·spring boot·后端·junit·postman
難釋懷8 天前
OpenResty基于ID负载均衡
junit·负载均衡·openresty
難釋懷9 天前
OpenResty-CJSON工具类
junit·openresty
難釋懷9 天前
OpenResty封装http工具
http·junit·openresty
難釋懷11 天前
OpenResty监听请求
junit·openresty
難釋懷11 天前
OpenResty获取参数的API
junit·openresty