Issue
I have an issue with one test checking that the entity with property version (annotated with @Version
) is incremented after an update.
- If I use the annotation
@SpringBootTest
the version is incremented. - If I use
@DataJpaTest
, the version is not incremented.
Do you know how to configure the @DataJpaTest
to make the incrementation work?
Please find below the working test:
@SpringBootTest
public class TestAuditing extends TestCrud<AuditingEntity> {
...
@Test
@Override
void update() {
Long version = entity.getVersion();
super.update();
assertEquals(++version, entity.getVersion());
}
}
And here is the not working test:
@ExtendWith(SpringExtension.class)
@DataJpaTest
public class TestAuditing extends TestCrud<AuditingEntity> {
...
@Test
@Override
void update() {
Long version = entity.getVersion();
super.update();
assertEquals(++version, entity.getVersion());
}
}
Here is the code of the TestCrud abstract class
public abstract class TestCrud<E extends AbstractEntity> {
protected static AbstractEntity entity;
...
@Test
void update() {
E updatedEntity = crudAdapter.update((E) entity);
assertEquals(updatedEntity.getId(), entity.getId());
entity = updatedEntity;
}
...
Thanks in advance for your answer!
Solution
I can't give a definitive answer because you didn't posted the code that actually is supposed to do anything. But the likely cause of the problem is that DataJpaTest
includes the @Transactioanl
annotation, thus moving the transaction boundaries from the entry and exit of the repository method, which I assume you use somewhere to the test method. Since JPA doesn't flush changes until the end of the transaction you don't get a version increment.
For tests like yours which depends on the exact scope of transactions I recommend using a TransactionTemplate
, so that you have exact control over your transactions. You can also use SQL logging to ensure that SQL statements get executed when you think they get executed.
Answered By - Jens Schauder
Answer Checked By - Marilyn (JavaFixing Volunteer)