har*_*are 3 java spring spring-test junit4
以下测试说明Spring将此测试bean初始化两次.我希望有人可以告诉我为什么会这样,因为它应该只有一次.这是测试:
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
Run Code Online (Sandbox Code Playgroud)
这是bean文件:
<?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>
Run Code Online (Sandbox Code Playgroud)
这是输出:
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
Run Code Online (Sandbox Code Playgroud)
这不是春季大会.你应该遵循JUnit约定,即套件范围的初始化或解构应该在@BeforeClass和@AfterClass中相应地完成,或者你可以使用@Autowire让Spring处理对象的范围.
将为每个测试构建一个新套件.这在JUnit3中更为明显,您必须使用指定的测试名称创建新套件.
看看JavaDoc:
Test annotation告诉JUnit它附加的公共void方法可以作为测试用例运行.要运行该方法,JUnit首先构造一个新的类实例,然后调用带注释的方法.JUnit将报告测试引发的任何异常为失败.如果没有抛出异常,则假定测试成功.
你的用例有点令人费解,因为你的测试实际上并没有做任何事情而且没有你引用的bean.默认情况下,Spring bean使用默认的scope ="singleton"属性声明,因此,如果您实际声明了一个bean,那么它将是一个缓存的单例.但是,这与方法执行无关.