ModelAspect { @Before(EXECUTION_SAVE) public void beforeSave(JoinPoint joinPoint) { for (Object object : joinPoint.getArgs()) { if (object instanceof BaseModel && (springContext.isAuthenticationContext() || springContext.isUnitTestContext())) { BaseModel<?> model = (BaseModel<?>) object; Date lastModifiedDate = new Date(); model.setLastModifiedDate(lastModifiedDate); User currentUser = userContext.getCurrentUser(); long currentUserId = currentUser.getId(); model.setLastModifiedUser(userRepository.findOne(idEqual(currentUserId)) .orElseThrow(() -> new IllegalArgumentException("No user found with id : " + currentUserId))); if (!model.exist() || model.getCreatedUser() == null) { long factualUserId = currentUser.getFactualUser().getId(); model.setCreatedDate(lastModifiedDate); model.setCreatedUser(userRepository.findOne(idEqual(factualUserId)) .orElseThrow(() -> new IllegalArgumentException("No user found with id : " + factualUserId))); } } } }  @Before(EXECUTION_SAVE) void beforeSave(JoinPoint joinPoint);  }
@Test public void testModelAspect() { Assume.assumeThat(springContext.isAuthenticationContext(), is(false)); JoinPoint joinPoint = mock(JoinPoint.class); @SuppressWarnings("unchecked") BaseModel<Object> baseModel = mock(BaseModel.class); when(joinPoint.getArgs()).thenReturn(new Object[] { baseModel }); modelAspect.beforeSave(joinPoint); verify(baseModel, times(1)).setCreatedDate(any(Date.class)); }
@Test public void testModelAspectOnServletContext() { springContext = spy(springContext); when(springContext.isAuthenticationContext()).thenReturn(true); JoinPoint joinPoint = mock(JoinPoint.class); @SuppressWarnings("unchecked") BaseModel<Object> baseModel = mock(BaseModel.class); when(baseModel.exist()).thenReturn(true); when(joinPoint.getArgs()).thenReturn(new Object[] { baseModel }); setField(modelAspect, "springContext", springContext); modelAspect.beforeSave(joinPoint); verify(baseModel, times(1)).setLastModifiedDate(any(Date.class)); }