【问题标题】:Failed to load ApplicationContext while running test cases运行测试用例时加载 ApplicationContext 失败
【发布时间】:2016-05-24 09:45:07
【问题描述】:

当我运行我的 spring 集成 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,我正在使用所有 spring 4.x jars。

这是我的堆栈跟踪..

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")

我在 google 中找到的一些地方是这样的

@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,没有 ant。 任何人都可以告诉我如何成功运行我的测试用例..

这是我的应用程序上下文。

<?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;
    }
    }

【问题讨论】:

  • 您的 applicationContext.xml 是否有 BpmProcessorDaoImplTest 的 bean 定义?
  • 请分享您的 applicationContext 文件。
  • 是的,它就在那里。我正在编辑我的代码,请检查。
  • 请也分享您的 BpmProcessorDaoImplTest。
  • 您的applicaitonContext.xml 在哪个文件夹中... 是否有任何更改/WEB-INF?如果是这样,那不是类路径的一部分。

标签: java spring junit


【解决方案1】:

1)

我在 web-inf 中有我的 applicationContext,我正在使用所有 spring 4.x jars。

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

所以简短而简单的解决方案是将弹簧配置文件放入:

  • (如果你使用 maven): src\main\resources
  • (如果你不使用maven):你的java源文件根文件夹
  • (如果你不使用 maven 而使用 eclipse): 创建一个额外的文件夹(例如 resources),将文件放在该文件夹中,然后将此文件夹设为 eclipse 源文件夹(右键单击该文件夹)包资源管理器中的文件夹,然后选择“构建路径”/“用作源文件夹”)

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());
   }
}

【讨论】:

  • 非常感谢您的回复,现在我得到了任何例外。但是在我的 dao 类 jdbc 模板和消息资源类中,这里是 null,这意味着 spring 没有为这些类创建对象。
  • 您可能还需要复制其他配置文件。
  • 我只有一个配置文件
  • @suri - 你的测试用例看起来很奇怪,看看我回答的第二部分。
【解决方案2】:

当在类路径中找不到applicationContext.xml时会发生这种情况

可能的解决方案:

  1. 将包含 applicationContext.xml 的目录添加到类路径。
  2. 给出applicationContext.xml的相对路径
  3. 给出applicationContext.xml的绝对路径

如果第三种解决方案对您有用,则意味着 applicationContext.xml 不在类路径中。

【讨论】:

  • hai 感谢您的回复,正如我之前提到的,我将 applicationContext,xml 保存在 web-inf 中,那么类路径呢
猜你喜欢
  • 2014-01-21
  • 1970-01-01
  • 1970-01-01
  • 2017-03-09
  • 2011-07-26
  • 1970-01-01
  • 2021-10-06
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多