I am using @Transactional for my JUnit tests (main advantage is rollback of changes within one test) but I have small problem that this influence my service transactions. So for example this is
my service :
@Service
@Transactional(propagation = Propagation.REQUIRED)
public class ServiceImpl
my unit test :
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "/test-context.xml" })
@Transactional
public class TestService
@Test
public void testNumberTransaction() {
Entity a = new Entity();
Entity b = new Entity();
service.add(a);
service.add(b);
}
So naively I expected to have two separate transactions for service.add() but unless I use @nontransactional on the test method it runs inside one transaction (but then it does not roll back after test).
Is this expected?Can I alter it with some configuration?
Thanks
Yes, it’s expected.
Propagation.REQUIRED(which is the default) means: execute in the existing transaction if it exists. Else, create a transaction and commit it at the end of the method.So yes, if the whole test method is transactional, both service calls will execute in the context of the test transaction.
Note that since the service is annotated with
REQUIRED, it’s supposed to work if a transaction already exists. This makes the test valid: it tests your service in the context of an existing transaction. If you want a service to execute in its own dedicated transaction, it should be annotated withREQUIRES_NEW. But of course, if it’s the case, you won’t be able to rollback the service transaction by executing the test in a transaction.