gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 10:44:22 29 4
gpt4 key购买 nike

当我运行我的 spring 集成 junit 类时,我遇到了异常。

这是我的类(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());

}
}

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

这是我的堆栈跟踪..

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

这是我的 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>

side test 源文件夹中的所有测试 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;
}
}

最佳答案

1)

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

web-inf 文件夹在运行测试时不可访问(没有 hack 和问题)。

因此,简短而简单的解决方案是将 spring 配置文件放入:

  • (如果你使用 maven): src\main\resources
  • (如果你不使用maven):你的java源文件根文件夹
  • (如果你用的不是maven而是eclipse):多建一个文件夹(比如resources),把文件放到那个文件夹里,然后做这个文件夹一个 Eclipse 源文件夹(在包资源管理器中右键单击该文件夹,然后选择“构建路径”/“用作源文件夹”)

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

要么它是一个测试用例 - 然后它的方法有 @Test 注释并且类本身有 @ContextConfiguration 配置指向你的配置文件。或者是一个 Repository 那么它有一个 @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());
}
}

关于java - 运行测试用例时无法加载 ApplicationContext,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37409914/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com