【问题标题】:Accessing spring context in testng's @BeforeTest在 testng 的 @BeforeTest 中访问 spring 上下文
【发布时间】:2012-04-28 09:37:58
【问题描述】:

我想在我的 @BeforeTest 方法中将一些 web 范围注册到 spring 上下文中。但事实证明,此时 spring 上下文仍然是null

如果我更改为@BeforeMethod,测试运行良好。我想知道如何访问@BeforeTest 中的上下文,因为我不希望每个测试方法都重复范围注册代码。

下面是我的代码 sn-ps。

public class MyTest extends MyBaseTest {
    @Test public void someTest() { /*...*/ }
}

@ContextConfiguration(locations="/my-context.xml")
public class MyBaseTest extends AbstractTestNGSpringContextTests {
    @BeforeTest public void registerWebScopes() {
        ConfigurableBeanFactory factory = (ConfigurableBeanFactory)
                this.applicationContext.getAutowireCapableBeanFactory();
        factory.registerScope("session", new SessionScope());
        factory.registerScope("request", new RequestScope());
    }   

    /* some protected methods here */
}

这是运行测试时的错误消息:

配置失败:@BeforeTest registerWebScopes java.lang.NullPointerException 在 my.MyBaseTest.registerWebScopes(MyBaseTest.java:22)

【问题讨论】:

    标签: java testng spring-test


    【解决方案1】:

    在您的 BeforeTest 方法中调用 springTestContextPrepareTestInstance()

    【讨论】:

    • 您是否知道任何关于为什么注入成员在 @BeforeTest 甚至 @BeforeSuite 方法中不可用的文档?
    • 10x :) 写 bean 后处理器更容易
    【解决方案2】:

    TestNG 在@BeforeClass 方法之前运行@BeforeTest 方法。 springTestContextPrepareTestInstance()@BeforeClass 注释并设置applicationContext。这就是为什么 applicationContext@BeforeTest 方法中仍然是 null 的原因。 @BeforeTest 用于 wapp 一组标记的测试。 (它不会在每个@Test 方法之前运行,所以有点用词不当。

    您可能应该使用@BeforeClass(在当前类中的第一个@Test 之前运行一次)而不是使用@BeforeTest。确保它依赖于springTestContextPrepareTestInstance 方法,如

    @BeforeClass(dependsOnMethods = "springTestContextPrepareTestInstance")
    public void registerWebScopes() {
        ConfigurableBeanFactory factory = (ConfigurableBeanFactory) 
                this.applicationContext.getAutowireCapableBeanFactory();
        factory.registerScope("session", new SessionScope());
        factory.registerScope("request", new RequestScope());
    }   
    

    @BeforeMethod 也可以工作(正如您所提到的),因为它们在 @BeforeClass 方法之后运行。

    【讨论】:

    • "@BeforeClass(在当前类中的任何 @Tests 之前运行)"。 TestNG documentation 中所述,@BeforeClass 将在当前类中的 first 测试方法被调用之前运行。
    • @JonyD,感谢您指出这一点,措辞不清楚。我已根据您的建议对其进行了编辑。
    猜你喜欢
    • 2018-03-16
    • 2017-06-18
    • 2015-08-15
    • 2012-01-22
    • 1970-01-01
    • 2011-04-16
    • 2013-12-09
    • 2018-11-21
    • 1970-01-01
    相关资源
    最近更新 更多