在 tomcat 7 上运行一个 web 应用程序,我的部署描述符包含 2 个监听器,一个是我创建的自定义监听器,另一个是 Spring:
<listener>
<listener-class>com.company.appName.web.context.MyContextListener</listener-class>
</listener>
<!-- Creates the Spring Container shared by all Servlets and Filters -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
当我运行我的集成测试时,我的监听器根本没有被调用,所以为了克服它我自己做了一些初始化(调用一些静态方法,这些方法基本上是从我的这个监听器调用的)。无论如何,我想我在这里遗漏了一些东西,听众什么时候被叫到?为什么在我的集成测试期间不会初始化?更具体地说,Spring 上下文确实得到了初始化,这是因为我在测试类的顶部声明了它:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "classpath:testApplicationContext.xml" })
所以 web.xml 从未实际使用过..
在这种情况下,spring context 总是首先被调用,在它被初始化之前我没有机会做任何事情 - 是这样吗?有没有办法在 spring 上下文之前运行一些代码?
更新: 我还想提一下,我在我的测试套件中使用了 @BeforeClass 注释:
@RunWith(Categories.class)
@IncludeCategory(HttpTest.class)
@SuiteClasses({ <MY TEST CLASSES> })
public class HttpSuiteITCase {
/**
* Run once before any of the test methods.
*/
@BeforeClass
public static void setTestsConfigurations() {
TestConfiguration.setup(false);
}
}
使用这种方法不能解决问题,测试类和我所有的 spring bean 首先被初始化。
提前致谢
最佳答案
用@BeforeClass
注释测试类中的static
方法并在那里进行初始化。例如:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration({ "classpath:testApplicationContext.xml" })
public class TestTest {
@BeforeClass
static public void beforeClass() {
// do intialization here
}
如果您的初始化代码需要访问类字段,因此不能是static
,那么您可以设置一个TestExecutionListener
。并实现 beforeTestClass()
。参见 this blog post举个例子。
关于spring - 在 spring 上下文初始化之前运行代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11604249/