suri
suri

Reputation: 433

Failed to load ApplicationContext while running test cases

when i am running my spring integration junit class i am getting above exception.

here is my class

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

    }
   }

i have my applicationContext inside web-inf and i am using all the spring 4.x jars.

here is my stack trace..

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

can any body please tell me how to write this line

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

some places in google i found like this

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

what is the difference of these two and when i am writing this line with stars i am getting different exception

here is my stack trace.

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

and one thing that my application is only dynamic web project no maven,no ant . can any body please tell me how to run my test cases successfully..

here is my 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>

all my test java files in side test source folder. and all the files in side the package's which prefix is com.tcs.test

here is my daoImpl class

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

Upvotes: 2

Views: 4251

Answers (2)

Ralph
Ralph

Reputation: 120861

1)

i have my applicationContext inside web-inf and i am using all the spring 4.x jars.

The web-inf folder is not (without hacks and problems) accessabel while running the tests.

So the short and easy solution is to put that spring config files in:

  • (if you use maven): src\main\resources
  • (if you do not use maven): your java source file root folder
  • (if you do not use maven but eclipse): create an extra folder (for example resources), put the files in that folder, and then make this folder a eclipse source folder (right click that folder in the package explorer and then choose "Build Path" / "Use as Source Folder")

2) your BpmProcessorDaoImplTest does not look like a valid test for me.

Either it is a Test case - then its methods have @Test annotations and the class itself have the @ContextConfiguration configuration that points to your configuration file. Or is is a Repository then it has a @Repository annotation and not @Test or @ContextConfiguration. annotations. But I never saw a class that mixed this.

So try this:

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

Upvotes: 1

Shirish Bari
Shirish Bari

Reputation: 2722

This will occure when applicationContext.xml cannot be found in class path

Possible solutions :

  1. add directory containing applicationContext.xml to classpath.
  2. give relative path of applicationContext.xml
  3. give absolute path of applicationContext.xml

If 3rd solution worked for you would mean that applicationContext.xml was not in classpath.

Upvotes: 0

Related Questions