2.8. Auditable entities

Suppose you want to keep track of who created user entities and who changed them. All you need to do is implement Auditable interface

Example 2.28. AuditableUser

@Entity
public class AuditableUser implements Auditable<User, Long> {

  @Id
  @GeneratedValue(strategy = GenerationType.AUTO)
  private Long id;

  private User createdUser;
  private Date createdDate;
  private User modifiedUser;
  private Date modifiedDate;

  // Getters and setters according to Auditable and 
  // Persistable omitted
}

Suppose you have the following three configuration files infrastructure.xml (for infrastructure setup), audition-context.xml (to setup the audition advice) and dao-context.xml (for the actual DAOs) the work of the AuditingAdvice can be demonstrated by the following testcase:

Example 2.29. Testcase for AuditingAdvice

@RunWith(SpringJUnit4ClassRunner.class)                                                  (1)
@ContextConfiguration(location = { "infrastructure.xml", 
  "audition-context.xml", "dao-context.xml" })
@Transactional
public class AuditionAdviceTest extends AbstractJpaTests {

  @Autowired
  private UserDao userDao;                                                               (2)

  @Autowired
  private AuditionAdvice advice;

  private AuditableUser user;                                                            (3)
  
  @Before
  public void setUp() {

    user = new AuditableUser();
    user.setUsername("username");
    user.setPassword("password");
    user.setEmailAddress("foo@bar.com");

    AuditorAware auditorAware = Mockito.mock(                                            (4)
      AuditorAware.class);
    Mockito.when(auditorAware.getCurrentUser())
      .thenReturn(user);

    advice.setAuditorAware();
  }

  @Test
  public void testApplicationOfAuditionAdvice() {

    user = userDao.save(user);

    assertEquals(user, user.getCreatedBy());
    assertNotNull(user.getCreationDate());

    assertEquals(user, user.getLastModifiedBy());
    assertNotNull(user.getLastModifiedDate());                                           (5)
  }
}

(1)

Configure the test class to be dependency injected and transactional.

(2)

References to Spring beans.

(3)

Test user to be inserted into the database.

(4)

Create a dummy User instance and a mock CurrentUserAware, that always returns the dummy user. Apply this mock to the advice.

(5)

The actual test simply saves the dummy User instance and verifys the advice got applied. Note that advice application is completely transparent to the client.