I am writing an app with Spring Boot + JPA, using a Postgres database. I have a User Entity and I am trying to get a timestamp when the user record is saved and/or modified.
My prefered solution is a set of multiple annotations to ensure test of @CreatedBy
or @CreatedDate
:
@RunWith(SpringRunner.class)
@DataJpaTest
@Import(JPAConfig.class)
@WithMockUser(username = "testuser")
public class MYRepositoryTest {
...
}
My Entities looks like:
@MappedSuperclass
@EntityListeners(AuditingEntityListener.class)
public class AbstractEntity {
@CreatedBy
private String createdBy;
@CreatedDate
private Date createdOn;
@LastModifiedDate
private Date updatedOn;
@LastModifiedBy
private String updatedBy;
}
My JPA configuration is:
@Configuration
@EnableJpaAuditing(auditorAwareRef = "auditorAware")
public class JPAConfig {
@Bean
public AuditorAware auditorAware() {
return () -> Optional.of(((User) SecurityContextHolder.getContext().getAuthentication().getPrincipal()).getUsername());
}
}
Now your audit fields also created during JPA test:
assertThat(result.getCreatedBy()).isNotNull().isEqualTo("testuser");
assertThat(result.getCreatedOn()).isNotNull();
assertThat(result.getUpdatedBy()).isNotNull().isEqualTo("testuser");
assertThat(result.getUpdatedOn()).isNotNull();