自定义注解作为 JUnit 中的列表注入

Custom Annotation inject as List in JUnit

我想要一个自定义 JUnit 注释,如果该注释存在于测试方法中,它应该使该对象的 List 可用于该测试方法,主要是通过作为方法参数。

Company 是包含 List<Employee> 的外部 class 对象,测试需要具有灵活性以拥有默认员工列表或提供自定义列表。

对于我的测试方法,我在相应的测试中处理注释,但是如何为所有测试文件(类似于 @BeforeMethod)添加此注释 运行 并且如果我的自定义注释存在于方法中,将其注入为 List<Employee>?

@Test
    @CompanyAnnotation(salary = 5)
    @CompanyAnnotation(salary = 50)
    public void testCompany(// Want to inject as method parameter of List<Employee> list) {

        for(Method method : CompanyTest.class.getDeclaredMethods()) {

                CompanyAnnotation[] annotations = method.getAnnotationsByType(
                        CompanyAnnotation.class);

                for(CompanyAnnotation d : annotations) {
                    System.out.println(b);
                }

        }

    }

===

class Company {
    // many other properties
    List<Employee> employeeList;

}

    class Employee {
       // more properties
      Integer age;
    }

    class CompanyBuilder {

    int defaultEmployeeSize = 10;

    public Company create(List<Employee> incoming) {
        List<Employee> employees = new ArrayList<>();

        employees.addAll(incoming);

        if ( employees.size() < defaultEmployeeSize )   {
            for(int i = 0; i < (defaultEmployeeSize - employees.size()); i++) {
                employee.add(new Employee());
            }
        }
        return employees;
    }
}

您可以拥有一个 BaseUnitTest class,它将具有 @Before 方法,注释解析。这样,它将适用于所有现有的单元测试。 请注意,这会稍微减慢总执行时间。

如何获取正在执行的测试方法 - Get name of currently executing test in JUnit 4

下面是您可以如何解决该问题的草图:

  1. 创建注释 CompanyAnnotation 以便它具有 @ExtendWith(CompanyAnnotationProcessor) 作为元注释。这将指示 Jupiter 使用 CompanyAnnotationProcessor 作为所有用 CompanyAnnotation 注释的测试方法的扩展。此外,CompanyAnnotation 必须是可重复的,这需要类似 CompanyAnnotationList 注释的东西。

  2. CompanyAnnotationProcessor 实现为 ParameterResolver

  3. 现在您必须在 CompanyAnnotationProcessor.resolveParameter 中获取原始方法注释。你这样做

    • 首先获取方法:Method method = (Method) parameterContext.getDeclaringExecutable();
    • 然后评估方法注释:org.junit.platform.commons.support.AnnotationSupport.findRepeatableAnnotations(method, CompanyAnnotation.class); 顺便说一句,AnnotationSupport 需要将 junit-platform-commons 添加到您的依赖项中。

现在您拥有创建具有注释中定义的薪水的员工的所有要素。