Skip to content

Instantly share code, notes, and snippets.

/gist:a6b76d13e75547de2203 Secret

Created Oct 3, 2013
Embed
What would you like to do?
@Component
@Accessors(chain=true)
public class ResetPasswordTokenServiceImpl implements ResetPasswordTokenService {
@Inject @Setter private RandomStringService randomStringService;
@Inject @Setter private TimeService timeService;
@Inject @Setter private PasswordResetTokenDao passwordResetTokenDao;
@Override
public PasswordResetToken generatePasswordResetTokenForUser(UUID userId){
// instead of using System.currentTimeMillis(), we externalize the call to a service, so we can track it easily
Long creationTime = timeService.getCurrentTime();
PasswordResetToken token = new PasswordResetToken();
token.setUserId(userId)
.setPasswordResetToken(randomStringService.generateRandomString())
.setIssuedTimestamp(creationTime)
.setValidTo(creationTime + DateTimeConstants.MILLIS_PER_DAY);
passwordResetTokenDao.save(token);
return token;
}
}
public class ResetPasswordTokenTest {
private ResetPasswordTokenService resetPasswordTokenService;
private RandomStringService randomStringService;
private TimeService timeService;
private PasswordResetTokenDao passwordResetTokenDao;
@Before
public void setup(){
// use mocks like me or create your own mocked implementations
randomStringService = mock(RandomStringService.class);
timeService = mock(TimeService.class);
passwordResetTokenDao = mock(PasswordResetTokenDao.class);
resetPasswordTokenService = new ResetPasswordTokenServiceImpl()
.setRandomStringService(randomStringService)
.setTimeService(timeService)
.setPasswordResetTokenDao(passwordResetTokenDao);
}
@Test
public void testResetPasswordTokenHasCorrectIssuedTimestampAndValidTo(){
UUID userId = UUID.randomId();
Long currentTime = System.currentTimeMillis();
// make the mocked service to always return the currentTime argument
when(timeService.getCurrentTime()).thenReturn(currentTime);
ResetPasswordToken token = resetPasswordTokenService.generatePasswordResetTokenForUser(userId);
// now we can easily make assertions about the issued time and the valid to
assertEquals(currentTime, token.getIssuedOn);
assertEquals(currentTime + DateTimeConstants.MILLIS_PER_DAY, token validTo);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment