运行测试用例时无法加载ApplicationContext

时间:2016-05-24 09:45:07

标签: java spring junit

当我运行我的spring integration junit类时,我正在超越异常。

这是我的班级

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:applicationContext.xml")
public class BpmControllerTest {

    @Autowired
   private BpmProcessorDaoImplTest bpmProcessorDao;  

    @Test
    public void testRun() throws UnexpectedInputException, ParseException, NonTransientResourceException, Exception {
    List<User>user=bpmProcessorDao.testRead();
     Assert.assertEquals(0,user.size());

    }
   }

我在web-inf中有我的applicationContext,我使用的是所有弹簧4.x罐。

这是我的堆栈跟踪..

Caused by: java.io.FileNotFoundException: class path resource [applicationContext.xml] cannot be opened because it does not exist
    at org.springframework.core.io.ClassPathResource.getInputStream(ClassPathResource.java:172)
    at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:330)
    ... 37 more

任何人都可以告诉我如何写这行

@ContextConfiguration(locations = "classpath:applicationContext.xml")
谷歌的一些地方我发现了这样的

@ContextConfiguration(locations = "classpath:**/applicationContext.xml")

这两者有什么不同 当我用星星写这行时,我得到了不同的异常

这是我的堆栈跟踪。

org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.tcs.test.dao.BpmProcessorDaoImplTest] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoSuchBeanDefinitionException(DefaultListableBeanFactory.java:1308)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1054)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:949)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:533)
    ... 28 more

有一点我的应用程序只是动态的web项目没有maven,没有蚂蚁。 可以告诉我如何成功运行我的测试用例..

这是我的applicationContext。

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:batch="http://www.springframework.org/schema/batch"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:task="http://www.springframework.org/schema/task" 
    xmlns:util="http://www.springframework.org/schema/util"
    xmlns:jdbc="http://www.springframework.org/schema/jdbc" 
    xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:aop="http://www.springframework.org/schema/aop"
    xmlns:jee="http://www.springframework.org/schema/jee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/batch
    http://www.springframework.org/schema/batch/spring-batch-2.2.xsd
    http://www.springframework.org/schema/beans 
    http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context-3.2.xsd
    http://www.springframework.org/schema/task
        http://www.springframework.org/schema/task/spring-task-3.2.xsd
        http://www.springframework.org/schema/util 
        http://www.springframework.org/schema/util/spring-util-3.2.xsd
        http://www.springframework.org/schema/jdbc 
        http://www.springframework.org/schema/jdbc/spring-jdbc-3.2.xsd
        http://www.springframework.org/schema/tx
        http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
        http://www.springframework.org/schema/aop 
        http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
        http://www.springframework.org/schema/jee 
        http://www.springframework.org/schema/jee/spring-jee-3.2.xsd
    ">
         <tx:annotation-driven />
          <tx:jta-transaction-manager/>
      <context:component-scan base-package="com.tcs.test" /> 

  <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
    <property name="driverClassName" value="oracle.jdbc.driver.OracleDriver" />
    <property name="url" value="jdbc:oracle:thin:@172.19.8.159:1521/OIM.itba.gov.in" />
    <property name="username" value="AppDB"></property>
    <property name="password" value="AppDB"></property>
    <property name="initialSize" value="2" />
    <property name="maxActive" value="5" />
    </bean>     

    <bean id="messageSource"
        class="org.springframework.context.support.ResourceBundleMessageSource">
        <property name="basename">
            <value>messages</value>
        </property>
    </bean>

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

   <bean id="runScheduler" class="com.tcs.controller.BpmControllerTest" />
       <task:scheduled-tasks>
    <task:scheduled ref="runScheduler" method="testRun" cron="0 0/1 * * * ?" />
   </task:scheduled-tasks>  
</beans>

我在侧测试源文件夹中的所有测试java文件。 包中所有文件的前缀是com.tcs.test

这是我的daoImpl类

package com.tcs.test.dao;

import java.io.ByteArrayInputStream;
import java.io.ObjectInputStream;
import java.sql.Blob;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;

import org.apache.log4j.Logger;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.support.ResourceBundleMessageSource;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.ResultSetExtractor;
import org.springframework.stereotype.Repository;

import com.tcs.controller.BPMConstants;
import com.tcs.controller.User;

@Repository
public class BpmProcessorDaoImplTest  implements BpmProcessorDaoTest{

    private static final Logger logger=Logger.getLogger(BpmProcessorDaoImplTest. class);


    @Autowired
    JdbcTemplate jdbcTemplate;

    @Autowired
    private ResourceBundleMessageSource messageSource;

    @Test
    public void testWrite() {
    }

    @Test
    public void testUpdateStatus() {
    }

    @Test
    public List<User> testRead() {

        String query=null;
        List<User>users=null;

        try{
    //  jdbcTemplate.setDataSource(dataSource); 
    //   query=messageSource.getMessage(BPMConstants.QUERY,null,Locale.US);
             query="select taskoutcome,seqNo,hash_mapdata,userid,status,taskId from com_tt_bpm_batch , "
                    + "wftask  where status='ACTIVE' and request_id=instanceid and state='ASSIGNED'";

         logger.info("query");
        jdbcTemplate.setFetchSize(20);


        users=jdbcTemplate.query(query, new ResultSetExtractor<List<User>>(){
             List<User> userList = new ArrayList<User>();

            @SuppressWarnings("unchecked")
            @Override
            public List<User> extractData(ResultSet rs) throws SQLException,DataAccessException {
                    while(rs.next()){
                    logger.info("fetching records from db");    
                    User user = new User();
                    user.setTaskOutcome(rs.getString(BPMConstants.TASK_OUTCOME));
                    user.setUserId(rs.getString(BPMConstants.USER_ID));
                    user.setStatus(rs.getString(BPMConstants.STATUS));
                    user.setTaskId(rs.getString(BPMConstants.TASK_ID));
                    user.setSeqNo(rs.getLong(BPMConstants.SEQ_NO));
                    user.setUserComment("nothing");
                    Blob blob=rs.getBlob(BPMConstants.HASH_MAPDATA);
                    try{
                    if(blob!=null && !blob.equals("")){
                    int blobLength = (int) blob.length();  
                    byte[] blobAsBytes = blob.getBytes(1, blobLength);
                    ByteArrayInputStream bos = new ByteArrayInputStream(blobAsBytes);
                    ObjectInputStream out=null;
                        out = new ObjectInputStream(bos);
                    HashMap<String, Object> map=null;
                        map = (HashMap<String, Object>)out.readObject();
                    user.setMap(map);
                    }
                    userList.add(user);
                    }catch(Exception e){
                        logger.error(e.getMessage());
                        logger.error("Exception at UserRowMapper class while reading data from blob  "+e.getStackTrace());
                    }
                    }
                return userList;
            }
        });
        }catch(Exception e){
            logger.error(e.getMessage());
            logger.error("Exception at UserRowMapper class while reading data from db  "+e.getStackTrace());
        }
        return users;
    }
    }

2 个答案:

答案 0 :(得分:1)

1)

  

我在web-inf中有我的applicationContext,我使用的是所有弹簧4.x罐。

运行测试时,web-inf文件夹不是(没有黑客和问题)accessabel。

所以简短的解决方案是将spring配置文件放在:

  • (如果你使用maven): src\main\resources
  • (如果你不使用maven):你的java源文件根文件夹
  • (如果你不使用maven但是eclipse):创建一个额外的文件夹(例如resources),将文件放在该文件夹中,然后使这个文件夹成为eclipse源文件夹(右键单击包浏览器中的该文件夹,然后选择&#34;构建路径&#34; /&#34;用作源文件夹&#34;)

2) 你的BpmProcessorDaoImplTest对我来说看起来不是一个有效的测试。

要么是测试用例 - 那么它的方法都有@Test注释,类本身具有指向配置文件的@ContextConfiguration配置。或者是一个存储库,然后它有一个@Repository注释,而不是@Test@ContextConfiguration。注释。但我从没见过一个混合了这个的课程。

所以试试这个:

@ContextConfiguration("classpath:applicationContext.xml")
@Transactional //make your tests run in an transaction that gets rolled back after the test
public class BpmProcessorDaoImplTest {

   /** Class under test */
   @Autowired
   private BpmProcessorDao dbmProcessorDao;

   @Autowired
   JdbcTemplate jdbcTemplate;

   @Autowired
   private ResourceBundleMessageSource messageSource;

   //just to make the example test usefull
   @PersistenceContext
   private EntityManager em

   @Test
   public void testWrite() {

      DbmProcessor entity = ...;
      ...
      this.dbmProcessorDao.save();
      ...
      em.flush();  //make sure that every is saved before clear
      em.clear();  //clear to make read(id) read the entity from the database but not from l1-cache.
      int id = entity.getId();          
      ...

      DbmProcessor reloadedEntity = this.dbmProcessorDao.read(id);

      //getName is just an example
      assertEquals(entity.getName(), dbmProcessorDao.getName());
   }
}

答案 1 :(得分:0)

在类路径

中找不到applicationContext.xml时会发生这种情况

可能的解决方案:

  1. 将包含 applicationContext.xml 的目录添加到classpath。
  2. 提供 applicationContext.xml
  3. 的相对路径
  4. 提供 applicationContext.xml
  5. 的绝对路径

    如果第3个解​​决方案适用于您,则意味着 applicationContext.xml 不在类路径中。

相关问题