【问题标题】:Getting NPE for @Autowired bean when using custom composed annotation in JUnit Jupiter在 JUnit Jupiter 中使用自定义组合注释时为 @Autowired bean 获取 NPE
【发布时间】:2019-04-11 19:16:29
【问题描述】:

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
}

【问题讨论】:

    标签: java spring-test junit5


    【解决方案1】:

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

    【讨论】:

    • 谢谢山姆。它通过添加@Retention(RetentionPolicy.RUNTIME) 起作用。感谢您的反馈。在花了几天时间试图解决列出的问题之后,这很有帮助。
    • 你能解释一下这个注释吗?它有效,但我真的不知道为什么?或者您可以指导我查看文档。
    • 我还注意到您添加了以下三个注释。我需要它们,因为我的代码没有它就可以工作吗?我试图在网上阅读它们,但并不完全了解它们的作用。@Target(ElementType.METHOD)@Documented@Inherited
    • 糟糕。我的意思是使用@Target(ElementType.TYPE)。这将其应用程序限制为您想要的类,因为在方法、字段等上使用自定义注释没有意义。
    • @Documented@Inheritable 是可选的。这些是标准的 Java 注释。因此,只需阅读他们的 Javadoc 和可选的有关 Java 注释的在线教程以获取更多信息。
    猜你喜欢
    • 2016-03-08
    • 1970-01-01
    • 1970-01-01
    • 2015-11-30
    • 2018-03-06
    • 2020-10-08
    • 2014-02-12
    • 2023-04-11
    • 1970-01-01
    相关资源
    最近更新 更多