代码之家  ›  专栏  ›  技术社区  ›  harschware

SpringJUnit4ClassRunner是否为每个测试初始化bean?

  •  3
  • harschware  · 技术社区  · 16 年前

    下面的测试说明这个测试bean由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
    
    1 回复  |  直到 16 年前
        1
  •  8
  •   Droo    16 年前

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

    看一看 JavaDoc

    测试注释告诉JUnit 它所使用的公共作废方法 附件可以作为测试用例运行。 到 然后是该类的新实例 调用带注释的方法。 任何 测试引发的异常将被删除 JUnit报告为失败。如果没有

    您的用例有点令人费解,因为您的测试实际上没有做任何事情,并且没有您引用的bean。默认情况下,springbean是使用defaultscope=“singleton”属性声明的,因此如果您实际声明了一个bean,那么它将是一个缓存的singleton。然而,这与方法执行无关。