JPA repository + @EntityListeners in JUnit tests

Viewed 3098

I have created Entity Listerner

public class SomeListener {
    @PrePersist
    @PreUpdate
    public void someAction(final SomeInterface entity) {

And added it to Entitites

@Entity
@EntityListeners(SomeListener.class)
public class SomeEntity implements SomeInterface {

Entities obtained from repository

@Repository
public interface SomeRepository
        extends JpaRepository<SomeEntity, Long>, JpaSpecificationExecutor<SomeEntity> {

In code it works fine, but in tests this listener is ignored

Test configuration:

@SpringBootApplication(scanBasePackages = {
        "package with listener",
        "package with model",
        "package with repository",
        "and all other packages"
})
@EnableJpaRepositories(basePackages = {
        "packages with repositories"
})
@EntityScan(basePackages = {
        "packages with models"
})
public class TestConfig {
}

Abstract class for Integration tests:

@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = TestConfig.class)
@AutoConfigureMockMvc
@Transactional
public abstract class AbstractTestInt {

and in test just called

mockMvc.perform(post(CREATE_URL).params(someparams))
.andExpect(status().is5xxServerError())

Entity listener should check some attributes and throw exception, because provided params wrong, but exception isn't thrown and in debugger I can see that parameters really wrong, so returned status redirection, as success save when called someRepository.save(entity)

Why Entity Listener not called in test context?

1 Answers

Here was problem not in tests, in my @PrePersist/@PreUpdate listener was additional check for access rights and thrown AccessDeniedException. When work @PrePersist - all is fine, because fired this event immediately, but @PreUpdate can be fired later, when transaction or some contexts is closed, and when this check tries to throw exception it tries to rollback transaction, that already closed, so it's causes another exception. For security of application it's okay - update request not sent, but not for tests.

Solution for this problem was in changing of repository.save() to repository.saveAndFlush() (that immediately causes writing to db and @PreUpdate event firing too)

Related