@Test
public void whenCAExists_andItIsAIntermediateCA_aValidChildCertificateIsGenerated()
  throws Exception {

  final KeyPair childCertificateKeyPair = setupKeyPair();
  final X500Name intermediateCaDn = new X500Name("O=foo,ST=bar,C=intermediate");
  final KeyPair intermediateCaKeyPair = fakeKeyPairGenerator.generate();
  final X509CertificateHolder intermediateCaCertificateHolder = makeCert(intermediateCaKeyPair,
    rootCaKeyPair.getPrivate(), rootCaDn, intermediateCaDn, true);
  final X509Certificate intermediateX509Certificate = new JcaX509CertificateConverter()
    .setProvider(BouncyCastleFipsProvider.PROVIDER_NAME)
    .getCertificate(intermediateCaCertificateHolder);
  final CertificateCredentialValue intermediateCa = new CertificateCredentialValue(
    null,
    CertificateFormatter.pemOf(intermediateX509Certificate),
    CertificateFormatter.pemOf(intermediateCaKeyPair.getPrivate()),
    null,
    true,
    false,
    false,
    false);
  when(certificateAuthorityService.findActiveVersion("/my-ca-name")).thenReturn(intermediateCa);
  when(keyGenerator.generateKeyPair(anyInt())).thenReturn(childCertificateKeyPair);
  final X509CertificateHolder childCertificateHolder = generateChildCertificateSignedByCa(
    childCertificateKeyPair,
    intermediateCaKeyPair.getPrivate(),
    intermediateCaDn
  );
  childX509Certificate = new JcaX509CertificateConverter()
    .setProvider(BouncyCastleFipsProvider.PROVIDER_NAME)
    .getCertificate(childCertificateHolder);
  when(
    signedCertificateGenerator
      .getSignedByIssuer(childCertificateKeyPair, inputParameters, intermediateX509Certificate, intermediateCaKeyPair.getPrivate())
  ).thenReturn(childX509Certificate);
  final CertificateCredentialValue certificateSignedByIntermediate = subject.generateCredential(inputParameters);
  assertThat(certificateSignedByIntermediate.getCa(),
    equalTo(intermediateCa.getCertificate()));
  assertThat(certificateSignedByIntermediate.getPrivateKey(),
    equalTo(CertificateFormatter.pemOf(childCertificateKeyPair.getPrivate())));
  assertThat(certificateSignedByIntermediate.getCertificate(),
    equalTo(CertificateFormatter.pemOf(childX509Certificate)));
  verify(keyGenerator, times(1)).generateKeyPair(2048);
}