无法使用Junit对弹簧工厂类进行单元测试

时间:2016-01-19 16:29:52

标签: java spring unit-testing spring-mvc junit

我正在尝试使用Spring JUnit对类进行单元测试并获得以下异常。

我的ProductDaoFactory类是一个单例类,其中只有一个非静态工厂方法。

错误日志:

Caused by: java.io.FileNotFoundException: class path resource [application-context.xml] cannot be opened because it does not exist
    at org.springframework.core.io.ClassPathResource.getInputStream(ClassPathResource.java:171)
    at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:329)
    ... 43 more

ProductDaoFactoryTest.java

@ContextConfiguration(locations = "classpath:application-context.xml")
@RunWith(SpringJUnit4ClassRunner.class)
public class ProductDaoFactoryTest {

    @Test
    public void testProductDaoFactory() {
        ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("application-context.xml");
        ProductDaoFactory productDaoFactory = (ProductDaoFactory) applicationContext.getBean("productDaoFactory");
        assertNotNull(productDaoFactory);
        applicationContext.close();
    }

}

ProductDaoFactory.java

public final class ProductDaoFactory {

    private static final ProductDaoFactory INSTANCE = new ProductDaoFactory();
    private String daoType;

    //so cannot new an intance
    private ProductDaoFactory() {
    }

    //singleton
    public static ProductDaoFactory getInstance() {
        return INSTANCE;
    }

    public void setDaoType(String daoType) {
        this.daoType = daoType;
    }

    //factory method
    public ProductDao getProductDao() {
        ProductDao productDao = null;

        if ("jdbc".equalsIgnoreCase(daoType)) {
            productDao = new ProductDaoJdbcImpl();
        } else if ("ibatis".equalsIgnoreCase(daoType)) {
            productDao = new ProductDaoIBatisImpl();
        } else if ("hibernate".equalsIgnoreCase(daoType)) {
            productDao = new ProductDaoHibernateImpl();
        }

        return productDao;
    }
}

WEB-INF /应用context.xml中

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
.....       
">

    <bean id="productDaoFactory" class="com.ministore.dao.factory.ProductDaoFactory" factory-method="getInstance"></bean>  
    <bean id="productDao" factory-bean="productDaoFactory" factory-method="getProductDao">
        <property name="daoType" value="jdbc" />
    </bean>  


    <!-- DATASOURCES AND DAO LAYER -->
    <!-- using JEE namespace for lookup -->
    <jee:jndi-lookup id="dataSource" jndi-name="jdbc/ministore-db" expected-type="javax.sql.DataSource" />

    <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
        <property name="dataSource" ref="dataSource"></property>
    </bean>

</beans>

0 个答案:

没有答案
相关问题