java – SpringJUnit4ClassRunner为每个测试初始化bean?
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了java – SpringJUnit4ClassRunner为每个测试初始化bean?,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2232字,纯文字阅读大概需要4分钟。
内容图文
![java – SpringJUnit4ClassRunner为每个测试初始化bean?](/upload/InfoBanner/zyjiaocheng/747/99e0a9e1c124429c804960277fa12164.jpg)
以下测试说明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
这是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>
这是输出:
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:
The Test annotation tells JUnit that
the public void method to which it is
attached can be run as a test case. To
run the method, JUnit first constructs
a fresh instance of the class then
invokes the annotated method. Any
exceptions thrown by the test will be
reported by JUnit as a failure. If no
exceptions are thrown, the test is
assumed to have succeeded.
你的用例有点令人费解,因为你的测试实际上并没有做任何事情而且你没有引用任何bean.默认情况下,Spring bean使用默认的scope =“singleton”属性声明,因此,如果您实际声明了一个bean,那么它将是一个缓存的单例.但是,这与方法执行无关.
内容总结
以上是互联网集市为您收集整理的java – SpringJUnit4ClassRunner为每个测试初始化bean?全部内容,希望文章能够帮你解决java – SpringJUnit4ClassRunner为每个测试初始化bean?所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。