本文介绍了SpringJUnit4ClassRunner是否为每个测试初始化​​bean?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下测试说明该测试bean由Spring初始化了两次.我希望有人能告诉我为什么会这样,因为它应该只有一次.这是测试:

The following test illustrates that this test bean is initialized twice by Spring. I'm hoping someone can tell me why this is so, since it should only be once. Here's the test:

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

推荐答案

这不是Spring约定.您应该遵循JUnit约定,即应在@BeforeClass和@AfterClass中相应地进行套件范围的初始化或解构,或者可以使用@Autowire并让Spring处理对象的作用域.

It's not a Spring convention. You should be following JUnit conventions, i.e. suite-wide initialization or deconstruction should be done in @BeforeClass and @AfterClass accordingly, or you can use @Autowire and let Spring handle the object's scope.

将为每个测试构建一个新套件.这在JUnit3中更加明显,在JUnit3中,您必须使用指定的测试名称来创建新套件.

A new suite will be constructed for each test. This is more apparent in JUnit3 where you had to create a new suite using a specified test name.

看看 JavaDoc :

您的用例有点令人费解,因为您的测试实际上没有做任何事情,并且没有供您引用的bean.默认情况下,Spring Bean是使用默认的scope ="singleton"属性声明的,因此,如果您实际上声明了Bean,它将是已缓存的单例.但是,这与方法执行无关.

Your use case is a bit puzzling since your test isn't actually doing anything and there is no bean, which you reference. By default, Spring beans are declared with the default scope="singleton" attribute, so had you actually declared a bean, it would have been a cached singleton. However, this has nothing to do with method execution.

这篇关于SpringJUnit4ClassRunner是否为每个测试初始化​​bean?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-29 20:39
查看更多