如何在JUnit测试(容器外部)中模拟TransactionManager? [英] How do I mock a TransactionManager in a JUnit test, (outside of the container)?
问题描述
我正在使用Spring 3.1.0.RELEASE,JUnit 4.8.1,最终将我的应用程序部署到JBoss 4.2服务器上(我知道,我知道).作为设置单元测试的一部分,我在Spring测试应用程序上下文中拥有了它.
I'm using Spring 3.1.0.RELEASE, JUnit 4.8.1, and ultimately deploying my application to a JBoss 4.2 server (I know, I know). As part of setting up my unit test, I have this in my Spring test application context ...
<bean id="transactionManager"
class="org.springframework.transaction.jta.JtaTransactionManager">
<property name="userTransactionName">
<value>UserTransaction</value>
</property>
</bean>
当然,现在这失败了,因为JNDI名称"UserTransaction"没有任何绑定.如何模拟交易管理器?我使用的是org.mockejb框架,但对任何合适的模拟框架都是开放的.
Of course, right now this fails because there is nothing bound to the JNDI name, "UserTransaction." How do I mock a transaction manager? I'm using the org.mockejb framework but an open to any suitable mocking frameworks.
推荐答案
我们只为事务管理器创建一个空的实现,并确保在单元测试使用的spring-context中使用该实现
We simply create an empty implementaion for the transaction manager, and ensure that this implementation is used in the spring-context used by the unit test
package sample;
import org.springframework.stereotype.Service;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionException;
import org.springframework.transaction.TransactionStatus;
public class MockedTransactionManager implements PlatformTransactionManager {
@Override
public TransactionStatus getTransaction(TransactionDefinition definition) throws TransactionException {
return null;
}
@Override
public void commit(TransactionStatus status) throws TransactionException {
}
@Override
public void rollback(TransactionStatus status) throws TransactionException {
}
}
..然后在spring-xml文件中看起来像..
.. and in the spring-xml file then looks like..
<bean id="transactionManager" class="sample.MockedTransactionManager"/>
这篇关于如何在JUnit测试(容器外部)中模拟TransactionManager?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!