3

We've got a Spring project that is using the AuditingEntityListener on our JPA entities:

@EntityListeners(AuditingEntityListener.class)

Our base entity has a lastModifiedDate defined as:

@Column(name = "modified_time")
@LastModifiedDate
@Temporal(TemporalType.TIMESTAMP)
private Date lastModifiedDate;

This value is being set automatically when the entity is saved or updated - which is how we'd like the application to behave. We run into issues, though, when we try to set up data in our test suites because in some situations (not all), we'd like to bypass the automatic setting of this field and set the value ourself. In this specific situation, we're trying to order a bunch of test data and then run a test against it.

Is there any way to bypass or turn off the AuditingEntityListener in order to create test data?

Chris Williams
  • 11,647
  • 15
  • 60
  • 97

2 Answers2

6

Declaring

@MockBean
private AuditingHandler auditingHandler

in your test should prevent the @LastModifiedDate from having any effect.

ryanp
  • 4,905
  • 1
  • 30
  • 39
  • Awesome! Here's the one when using Mockk / kotlin: @MockkBean(relaxed = true) private lateinit var auditingHandler: AuditingHandler – Boni2k Apr 07 '21 at 17:44
0

I can imagine the following solution: create two persistence.xml files - one for production and another for testing purposes:

  • the production related persistence.xml includes reference to orm_production.xml mapping file that specifies AuditingEntityListener with entity-listener attribute

  • the tests related persistence.xml may include reference to orm_test.xml maping file that specifies AuditingEntityListener with entity-listener attribute. Additionally, your base entity needs to be defined entirely within xml mapping file and specify:

    • metadata-complete attribute: tells the provider to ignore in-code annotations
    • exclude-default-listeners attribute: tells the provider to ignore entity listeners but only for the corresponding base entity
wypieprz
  • 7,981
  • 4
  • 43
  • 46