JUnit 5 自定义注解:方法级 JSON 参数注入
实现 在测试方法上使用注解,并通过注解属性指定参数名称和 JSON 字符串(转换为 Java 对象)
一、实现步骤
1. 定义自定义注解
创建一个注解 @JsonTest,用于在测试方法上指定参数名和 JSON 字符串。
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface JsonTest {
String parameterName(); // 方法参数的名称
String jsonValue(); // JSON 字符串
}
2. 实现 BeforeEachCallback
在测试方法执行前解析注解,将 JSON 转换为对象并存储到上下文。
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.jupiter.api.extension.BeforeEachCallback;
import org.junit.jupiter.api.extension.ExtensionContext;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
public class JsonParameterPreprocessor implements BeforeEachCallback {
private static final ObjectMapper objectMapper = new ObjectMapper();
@Override
public void beforeEach(ExtensionContext context) throws Exception {
Method testMethod = context.getRequiredTestMethod();
if (testMethod.isAnnotationPresent(JsonTest.class)) {
JsonTest annotation = testMethod.getAnnotation(JsonTest.class);
String parameterName = annotation.parameterName();
String jsonValue = annotation.jsonValue

最低0.47元/天 解锁文章
945

被折叠的 条评论
为什么被折叠?



