gpt4 book ai didi

java - 在 testng 的 @BeforeTest 中访问 spring 上下文

转载 作者:搜寻专家 更新时间:2023-10-31 08:15:37 35 4
gpt4 key购买 nike

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

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

下面是我的代码片段。

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

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

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

最佳答案

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

关于java - 在 testng 的 @BeforeTest 中访问 spring 上下文,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10184602/

35 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com