@Test
public void mapUuidsToKeys_whenTheActiveKeyIsTheOnlyKey_whenThereIsNoMatchingCanaryInTheDatabase_whenDecryptingWithTheWrongKeyRaisesAnInternalException_itShouldCreateACanaryForTheKey()
  throws Exception {

  when(encryptionKeysConfiguration.isKeyCreationEnabled()).thenReturn(true);
  when(encryptionKeysConfiguration.getProviders().get(0).getKeys()).thenReturn(asList(activeKeyData));
  when(encryptionKeysConfiguration.getProviders()).thenReturn(asList(activeProvider));
  final EncryptionKeyCanary nonMatchingCanary = new EncryptionKeyCanary();
  nonMatchingCanary.setUuid(UUID.randomUUID());
  nonMatchingCanary.setEncryptedCanaryValue("fake-non-matching-encrypted-value".getBytes(UTF_8));
  nonMatchingCanary.setNonce("fake-non-matching-nonce".getBytes(UTF_8));
  when(encryptionKeyCanaryDataService.findAll())
    .thenReturn(asArrayList(nonMatchingCanary));
  when(encryptionService
    .decrypt(activeKey, nonMatchingCanary.getEncryptedCanaryValue(),
      nonMatchingCanary.getNonce()))
    .thenThrow(new AEADBadTagException());
  when(encryptionKeyCanaryDataService.save(any(EncryptionKeyCanary.class)))
    .thenReturn(activeKeyCanary);
  when(encryptionService.encrypt(any(EncryptionKey.class), eq(CANARY_VALUE))).thenReturn(new EncryptedValue(
    null,
    "fake-encrypted-value",
    "fake-nonce"));
  subject = new EncryptionKeyCanaryMapper(encryptionKeyCanaryDataService,
    encryptionKeysConfiguration, timedRetry, providerFactory);
  subject.mapUuidsToKeys(keySet);
  assertCanaryValueWasEncryptedAndSavedToDatabase();
}