基于SpringJUnit4ClassRunner初始化为每个测试豆?
-
21-09-2019 - |
题
下面的试验说明,这个测试豆被Spring初始化两次。我希望有人能告诉我为什么会这样,因为它应该只是一次。这里的测试:
import org.apache.log4j.Logger;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {} )
public class TestAfterPropsSet implements InitializingBean {
private static final Logger logger = Logger.getLogger(TestAfterPropsSet.class);
@Test
public void test1() {
logger.debug("Test1");
}
@Test
public void test2() {
logger.debug("Test2");
}
public void afterPropertiesSet() throws Exception {
logger.debug("Bean Initialized");
}
} // end class
这里的豆文件:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
</beans>
和这里的输出:
2009-10-13 21:20:04,393 [TestAfterPropsSet.java 26] DEBUG - Bean Initialized
2009-10-13 21:20:04,393 [TestAfterPropsSet.java 17] DEBUG - Test1
2009-10-13 21:20:04,393 [TestAfterPropsSet.java 26] DEBUG - Bean Initialized
2009-10-13 21:20:04,393 [TestAfterPropsSet.java 22] DEBUG - Test2
解决方案
这不是一个春天的约定。你应该下面的JUnit惯例,即套件范围内的初始化或解构应该@BeforeClass和@AfterClass来完成相应的,也可以使用@Autowire并让Spring处理对象的范围。
一个新套件将被构造为每个测试。这是在JUnit3更加明显,其中你有使用指定的测试名称创建一个新的套件。
看一看的的JavaDoc :
在测试注解告诉JUnit的那 所述公共无效方法,其是 附着可以运行作为一个测试用例。 要 运行的方法,JUnit的第一构建体 类的新实例,然后 调用注解的方法。强>任何 由测试抛出的异常会 通过JUnit的作为失败的报道。如果不 引发异常,测试 假设已经成功了。
您的使用情况是有点令人费解,因为测试实际上没有做任何事情,没有豆,你参考一下。默认情况下,Spring bean的声明与默认范围=“单身”的属性,让你有实际声明一个bean,它会一直缓存的单例。然而,这具有无关方法执行。
不隶属于 StackOverflow