我正在尝试对我正在编写的Web服务中使用的部分代码运行高级别测试。在此过程中,代码应该调用数据库(我使用Spring和Hibernate设置)。自动装配在测试用例类本身中运行良好,但是由于运行测试而被调用的其他类不是自动装配的。
单元测试
@RunWith( SpringJUnit4ClassRunner.class )
@ContextConfiguration
public class ProviderTest
{
@Autowired
protected ApplicationContext applicationContext;
protected ProviderA provider;
@Before
public void setUp()
{
Transaction transaction = DbLogHelper.getInstance().getLog();
transaction.setCompanyName("Unit Test");
transaction.setCreateTime(Calendar.getInstance());
transaction.setPhoneNumber("Provider Test - N/A");
transaction.setQueryId("Unit Test");
transaction.setRequest("<NONE - UNIT TEST>");
transaction.setResponse("<NONE - UNIT TEST>");
LogJob job = new LogJob(transaction, DbLogHelper.getInstance.getDao());
job.run();
provider = new ProviderA(transaction);
}
@After
public void tearDown()
{
Transaction transaction = DbLogHelper.getInstance().getLog();
transaction.setResponseTime(Calendar.getInstance());
DbLogHelper.getInstance().writeLog(transaction);
DbLogHelper.getInstance().resetLog();
}
@Test
public void testProvider()
{
try
{
List<TAddress> results = provider.searchItem("SOME_ITEM", "12345");
Assert.assertNotNull(results);
}
catch (Exception e)
{
Assert.fail();
}
}
}
Singleton Log Helper
public class DbLogHelper
{
private static DbLogHelper instance;
@Autowired
private LogDao dao;
private Executor executor = new ThreadPoolExecutor(3, 10, 10, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>());
private ThreadLocal<Transaction> transactionRef = new ThreadLocal<Transaction>() {
@Override
protected Transaction initialValue()
{
return new Transaction();
}
};
public static DbLogHelper getInstance()
{
if (instance == null)
{
synchronized (DbLogHelper.class)
{
if (instance == null)
{
instance = new DbLogHelper();
}
}
}
return instance;
}
/**
* Gets the Transaction object attached to this thread. Generates a new one if it does not
* yet exist.
* @return Transaction
*/
public Transaction getLog()
{
return transactionRef.get();
}
/**
* Removes the current Transaction object from the thread map. The next getLog() call will
* generate a new one.
*/
public void resetLog()
{
transactionRef.remove();
}
/**
* Gets the DAO used to persist Transaction objects
*/
public LogDao getDao()
{
return dao;
}
/**
* Queues the passed Transaction object to be written to the database. This happens in a
* separate thread so the service is not waiting on database persistence before responding.
* @param transaction
*/
public void writeLog(Transaction transaction)
{
LogJob job = new LogJob(transaction, dao);
executor.execute(job);
}
}
记录DAO
@Repository
public class LogDao
{
private static Logger log = LoggerFactory.getLogger(LogDao.class);
private EntityManager entityManager;
@PersistenceContext
public void setEntityManager(EntityManager entityManager) {
log.debug("Entity Manager set on LogDao");
this.entityManager = entityManager;
}
@Transactional
public void updateTransaction(Transaction log)
{
log = entityManager.merge(log);
}
}
ProviderTest-context.xml中
<!-- database -->
<bean id="datasource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<!-- uncomment to see sql
<property name="driverClassName" value="com.p6spy.engine.spy.P6SpyDriver" />
-->
<property name="url" value="jdbc:mysql://localhost" />
<property name="username" value="root" />
<property name="password" value="" />
</bean>
<!-- LOCAL entity manager factory -->
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<!-- <property name="persistenceUnitManager" ref="persistenceUnitManager"/> -->
<property name="persistenceUnitName" value="domainPersistenceUnit" />
<property name="dataSource" ref="datasource" />
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="showSql" value="false" />
<!-- <property name="generateDdl" value="true" /> -->
<property name="databasePlatform" value="org.hibernate.dialect.MySQLDialect" />
</bean>
</property>
</bean>
<bean class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor"/>
<bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor" />
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
<property name="dataSource" ref="datasource" />
</bean>
<context:annotation-config/>
<context:component-scan base-package="com.company.application.webservice"/>
DbLogHelper中的自动装配DAO始终为空。但是,如果我直接在单元测试中自动将其自动装入,它就会很好地注入实体经理准备就绪。当然,我担心的是,如果它不在测试中,那么在正确部署时它将无法工作。即使我不必担心,我仍然想测试它。
答案 0 :(得分:1)
DBLogger不是一个spring bean,所以spring不能将任何类Autowire给它(因为它不知道它)。我建议在spring上下文中将它定义为bean,并将DbLogHelper注入你想要使用它的任何类中。
答案 1 :(得分:0)
您应该将@John Vint提到的DBLogger定义为spring bean,或者如果由于某种原因无法定义,则可以从spring应用程序上下文中获取要自动装配的对象(不推荐)。
有关后者的详情: http://www.javacodegeeks.com/2015/03/using-spring-managed-bean-in-non-managed-object.html