首页 > 解决方案 > 在 JUnit Jupiter 中使用自定义组合注释时为 @Autowired bean 获取 NPE

问题描述

TransactionalIntegrationTest.java

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

我的测试测试.java

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

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

createUser.

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

我的TestTest.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
}

标签: javaspring-testjunit5

解决方案


您可能缺少@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 {
}

推荐阅读