简体   繁体   中英

How to override JPA @PrePersist behaviour for a unit test

I have the following JPA entity:

@Entity
@Builder
@Table(name = "My_Table")
public class MyTableEntity {

    @Column(name = "id")
    private long id;

    @Column(name = "creationdatetime")
    private LocalDateTime creationDateTime;

    @Column(name = "updatedatetime")
    private LocalDateTime updateDateTime;

    @PrePersist
    protected void onCreate() {
    this.creationDateTime = LocalDateTime.now();
        this.updateDateTime = LocalDateTime.now();
    }
}

I have a unit test where I am doing this:

   LocalDateTime creationDate = LocalDateTime.now().minusDays(100);
   MyTableEntity entity = 
   MyTableEntity.builder()
           .id(1)
           .build();
   entity.setCreationDateTime(creationDate)
   entity.setUpdateDateTime(creationDate)

However, later on in my unit test, the value I'm setting for creation date time and update date time is magically getting changed as per what is defined in the @PrePersist method in my JPA entity.

Solely for the purpose of unit testing, how can I stop @PrePersist from overriding values I'm explicitly setting during the unit test?

(If it, helps I am using Mockito.)

The easiest way is adding check in the MyTableEntity#onCreate method:

@PrePersist
protected void onCreate() {
    if(creationDateTime == null){
        this.creationDateTime = LocalDateTime.now();
    }
    if(updateDateTime == null){
        this.updateDateTime = LocalDateTime.now();
    }
}

Then the values you set in the unit test won't be rewritten.

Another option is passing onCreate code from outside.

@Entity
@Builder
@Table(name = "My_Table")
public class MyTableEntity {

    ///  ... 

    @Transient
    private Consumer<MyTableEntity> onCreateConsumer = mte -> {
        mte.creationDateTime = LocalDateTime.now();
        mte.updateDateTime = LocalDateTime.now();
    };

    @PrePersist
    protected void onCreate() {
        onCreateConsumer.accept(this);
    }
}

Then you will be able to set onCreateConsumer in the unit test:

MyTableEntity.builder()
   .id(1)
   .onCreateConsumer(e -> {}) // do nothing
   .build();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM