Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I mock a TransactionManager in a JUnit test, (outside of the container)?

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>

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.

like image 336
Dave Avatar asked Aug 02 '12 18:08

Dave


People also ask

What is mocking in JUnit testing?

Mocking is a technique of unit testing a class, where we mock an external dependency in order to test our classes and methods. When unit tests are written well with mocks, they would not have any external dependencies and will not fail when external stuff changes. We looked at the Mockito framework.

Does JUnit have mocking?

While doing unit testing using junit you will come across places where you want to mock classes. Mocking is done when you invoke methods of a class that has external communication like database calls or rest calls.


1 Answers

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 {

    }

}

.. and in the spring-xml file then looks like..

<bean id="transactionManager" class="sample.MockedTransactionManager"/>
like image 200
Urobe Avatar answered Oct 10 '22 15:10

Urobe