访问testng的@BeforeTest中的spring上下文 [英] Accessing spring context in testng's @BeforeTest

查看:178
本文介绍了访问testng的@BeforeTest中的spring上下文的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I would like to register some web scopes to the spring context in my @BeforeTest method. But it turns out that spring context is still null at that point.

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

The test runs fine though, if I change into @BeforeMethod. I wonder how I can access the context in @BeforeTest, because I don't want the scope registration code to be repeated for each test methods.

以下是我的代码段。

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 */
}

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

Here's the error message when running the test:


FAILED CONFIGURATION: @BeforeTest registerWebScopes
java.lang.NullPointerException
    at my.MyBaseTest.registerWebScopes(MyBaseTest.java:22)


推荐答案

在BeforeTest方法中调用 springTestContextPrepareTestInstance()

Call springTestContextPrepareTestInstance() in your BeforeTest method.

这篇关于访问testng的@BeforeTest中的spring上下文的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆