【问题标题】:How to unit test Lombok @SneakyThrows annotation existence under method如何对方法下的 Lombok @SneakyThrows 注释进行单元测试
【发布时间】:2023-02-09 17:15:08
【问题描述】:
   @Test
    void annotatedClass() throws NoSuchMethodException {
        Class<? extends service> aClass = underTest.getClass();
        Method method = aClass.getDeclaredMethod("create", param.class);
        method.setAccessible(true);
        SneakyThrows sneakyThrows = method.getAnnotation(SneakyThrows.class);
        Assertions.assertNotNull(sneakyThrows);
    }

但是 assert 是 Null 并且私有方法用 @SneakyThrows 注释

想法谈话: 注释“SneakyThrows.class”未保留用于反射访问

我们能否击败注释保留并能够以某种方式对其进行测试?

【问题讨论】:

  • Lombok 用实际代码替换注释。注释在编译过程中被删除,这是 AFAIK 无法比拟的。但是,您可以通过使用导致异常的参数调用方法来测试注释是否真的会触发

标签: java unit-testing lombok


【解决方案1】:

据我了解,Lombok 的@SneakyThrows 保留SOURCE,因此它不会保留在编译代码中。查看来源:

@Target({ElementType.METHOD, ElementType.CONSTRUCTOR})
@Retention(RetentionPolicy.SOURCE)
public @interface SneakyThrows {
    /** @return The exception type(s) you want to sneakily throw onward. */
    Class<? extends Throwable>[] value() default java.lang.Throwable.class;
    
    //The fully qualified name is used for java.lang.Throwable in the parameter only. This works around a bug in javac:
    //   presence of an annotation processor throws off the type resolver for some reason.
}

java.lang.annotation.RetentionPolicy的来源:

public enum RetentionPolicy {
    /**
     * Annotations are to be discarded by the compiler.
     */
    SOURCE,

    /**
     * Annotations are to be recorded in the class file by the compiler
     * but need not be retained by the VM at run time.  This is the default
     * behavior.
     */
    CLASS,

    /**
     * Annotations are to be recorded in the class file by the compiler and
     * retained by the VM at run time, so they may be read reflectively.
     *
     * @see java.lang.reflect.AnnotatedElement
     */
    RUNTIME
}

【讨论】:

    猜你喜欢
    • 2017-09-13
    • 2018-10-17
    • 1970-01-01
    • 2018-03-26
    • 1970-01-01
    • 2011-08-12
    • 2021-07-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多