Java JUnit中的自定义注释注入为列表
我想要一个自定义JUnit注释,如果该注释出现在测试方法上,它应该使该对象的Java JUnit中的自定义注释注入为列表,java,junit,annotations,junit5,Java,Junit,Annotations,Junit5,我想要一个自定义JUnit注释,如果该注释出现在测试方法上,它应该使该对象的列表可用于该测试方法,主要是作为方法参数 Company是一个外部类对象,它包含List,测试需要具有灵活性,以拥有默认员工列表或提供自定义列表 对于我的测试方法,我在各自的测试中处理注释,但是我如何让该注释对所有测试文件运行(类似于@BeforeMethod),如果我的自定义注释出现在方法上,则将其作为列表插入 @测试 @公司名称(工资=5) @公司名称(工资=50) public void testCompany(/
列表
可用于该测试方法,主要是作为方法参数
Company
是一个外部类对象,它包含List
,测试需要具有灵活性,以拥有默认员工列表或提供自定义列表
对于我的测试方法,我在各自的测试中处理注释,但是我如何让该注释对所有测试文件运行(类似于@BeforeMethod
),如果我的自定义注释出现在方法上,则将其作为列表
插入
@测试
@公司名称(工资=5)
@公司名称(工资=50)
public void testCompany(//要作为列表的方法参数注入){
对于(方法:CompanyTest.class.getDeclaredMethods()){
CompanyNotation[]annotations=method.getAnnotationsByType(
公司名称(表示法.class);
用于(公司注释d:注释){
系统输出打印ln(b);
}
}
}
===
class公司{
//许多其他财产
员工名单;
}
班级员工{
//更多属性
整数年龄;
}
类公司生成器{
int defaultEmployeeSize=10;
上市公司创建(输入列表){
List employees=new ArrayList();
employees.addAll(传入);
if(employees.size()
您可以拥有一个BaseUnitTest类,它将作为@Before方法包含注释解析。这样,它将应用于所有现有的单元测试。
请注意,这将使总执行时间减慢一点
如何获得正在执行的测试方法-以下是如何解决该问题的示意图:
companynotation
,使其具有@extendedwith(companynotationprocessor)
作为元注释。这将指示Jupiter使用companynotationProcessor
作为使用companynotation
注释的所有测试方法的扩展。此外,companynotation
必须是可重复的,这需要类似于companynotationlist
注释的东西companynotationprocessor
作为ParameterResolver
实现companynotationprocessor.resolveparmeter
中找到原始方法注释。你是靠你自己做的吗
- 首先获取方法:
methodmethod=(method)parameterContext.getDeclaringExecutable()代码>
- 然后评估方法注释:
顺便说一句,org.junit.platform.commons.support.AnnotationSupport.findRepeatableAnnotations(方法,companynotation.class);
需要将AnnotationSupport
添加到依赖项中junit平台共用项
现在,您已经具备了创建具有注释中定义的薪资的员工的所有要素 如果我理解正确,您是说
BaseUnitTest
将被所有现有测试用例扩展。这将是一个巨大的项目变化。我假设这是一个新项目。如果您使用的是Spring,那么您可以使用AOP来实现这一点(我将详细说明它是否对您可行),或者您可以将它用于具有注释的特定类上。谢谢!我没有用弹簧。如果可行的话,我正在寻找一些关于动态注入方法代理作为方法参数的东西。设置一个测试套件并在那里添加注释解析逻辑怎么样?并使用通配符,这听起来是一个很好的方法!我的问题似乎非常类似于JUnit在注入参数流时如何使用@MethodSource
/@ValueSource
。不过在我的例子中,我想注入一个对象列表
@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;
}
}