@Test
public void storeSecrets_existingSecret() throws Exception {

    //GIVEN
    final TypedSecret typedSecret = new TypedSecret();
    typedSecret.setSecretType(SecretType.E_METER_MASTER_KEY);
    typedSecret.setSecret(HexUtils.toHexString("$3cr3t".getBytes()));
    final DbEncryptionKeyReference keyReference = new DbEncryptionKeyReference();
    keyReference.setEncryptionProviderType(EncryptionProviderType.JRE);
    keyReference.setReference("keyReferenceString");
    final EncryptedSecret encryptedSecret = new EncryptedSecret(EncryptionProviderType.JRE, "$3cr3t".getBytes());
    final DbEncryptedSecret existingDbSecret = new DbEncryptedSecret();
    existingDbSecret.setCreationTime(new Date());
    existingDbSecret.setSecretType(SecretType.E_METER_MASTER_KEY);
    existingDbSecret.setEncodedSecret("1234567890ABCDEF");
    existingDbSecret.setDeviceIdentification("SOME_DEVICE");
    existingDbSecret.setEncryptionKeyReference(keyReference);
    //WHEN
    when(this.secretRepository.findIdOfValidMostRecent(any(), any(), any())).thenReturn(1L);
    when(this.secretRepository.findById(1L)).thenReturn(Optional.of(existingDbSecret));
    when(this.keyRepository.findByTypeAndValid(any(), any(), any())).thenReturn(
            new PageImpl<>(Arrays.asList(keyReference)));
    when(this.encryptionDelegate.decrypt(any(), any())).thenReturn(
            new Secret(existingDbSecret.getEncodedSecret().getBytes()));    //decrypt existing DB secret
    when(this.encryptionDelegate.encrypt(any(), any(), anyString())).thenReturn(
            encryptedSecret);   //encrypt new DB secret
    this.service.storeSecrets("SOME_DEVICE", Arrays.asList(typedSecret));
    //THEN
    final ArgumentCaptor<DbEncryptedSecret> secretArgumentCaptor = ArgumentCaptor.forClass(DbEncryptedSecret.class);
    verify(this.secretRepository).save(secretArgumentCaptor.capture());
    final DbEncryptedSecret savedSecret = secretArgumentCaptor.getValue();
    assertThat(savedSecret).isNotNull();
    assertThat(savedSecret.getDeviceIdentification()).isEqualTo("SOME_DEVICE");
    assertThat(savedSecret.getSecretType()).isEqualTo(typedSecret.getSecretType());
    assertThat(savedSecret.getEncodedSecret()).isEqualTo(HexUtils.toHexString(encryptedSecret.getSecret()));
    assertThat(savedSecret.getEncryptionKeyReference()).isEqualTo(keyReference);
    assertThat(savedSecret.getCreationTime()).isNotNull();
}