在 JUnit Jupiter 中使用自定义组合注释时获取 @Autowired bean 的 NPE

Getting NPE for @Autowired bean when using custom composed annotation in JUnit Jupiter

TransactionalIntegrationTest.java

@TestMethodOrder(OrderAnnotation.class)
@SpringJUnitWebConfig(locations = { "classpath:service.xml","classpath:data.xml" })
@Tag("1")
public @interface TransactionalIntegrationTest {}

MyTestTest.java

@TransactionalIntegrationTest
public class MyTestTest {
@Autowired
protected CreateUser createUser;

@BeforeEach
public void setUp() throws Exception {
createUser.createTimesheetUser(...)} --> NPE
}

createUser 上获取 NullPointerException。

如果我不使用元注释,那么它工作正常。

MyTestTest.java

@TestMethodOrder(OrderAnnotation.class)
@SpringJUnitWebConfig(locations = { "classpath:service.xml","classpath:data.xml" })
@Tag("1")
public class MyTestTest {
@Autowired
protected CreateUser createUser;

@BeforeEach
public void setUp() throws Exception {
createUser.createTimesheetUser(...)} --> works now
}

您可能缺少 @Retention 声明,该声明允许 Spring 和 JUnit 等框架在运行时查看注释。

按如下方式声明您的组合注释应该有效。

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@TestMethodOrder(OrderAnnotation.class)
@SpringJUnitWebConfig(locations = { "classpath:service.xml", "classpath:data.xml" })
@Tag("1")
public @interface TransactionalIntegrationTest {
}