8

The .setClientCertificateName method of the HttpRequest class requires a string that is the name of a certificate in the organization.

In a unit test class, is it possible to mock this method? When I call it in a scratch org (that has no certificates) I get the following exception:

System.CalloutException: Could not find client cert with dev name

5
  • Are you using @isTest(SeeAllData=true) on your test? If you get the same exception with that annotation, then I would conclude it's not possible to reference the certificates in a unit test. You also cannot make an actual callout in a unit test (you must use an Http Mock class) so I would not worry about missing any vital functionality by being unable to specify a certificate in your unit test.
    – nbrown
    Commented Aug 16, 2019 at 14:35
  • I want to know if I can somehow mock the certificate, since I don't have it in my organization. My tests don't use the "see all data" annotation. Commented Aug 16, 2019 at 14:41
  • There is no way to create certificates in Apex code, so your only option would be to allow the unit test to see all data and then maybe it will be able to find the certificate in the org. I haven't used certificates in HTTP callouts before so this is my best guess. The documentation on Salesforce doesn't mentioned testing this scenario.
    – nbrown
    Commented Aug 16, 2019 at 14:47
  • Yup, the docs don't mention this use case. I'm wondering if anyone else had the same issue. I suspect that this scenario requires the Test.isRunningTest method, to set the certificate or not (for example: if I only have the certificate on my production org and it is not available on scratch orgs or sandboxes). Commented Aug 16, 2019 at 14:52
  • 1
    @RenatoOliveira I think you have figured it out, the best bet is Test.isRunningTest() to be able to fork out the execution flow depending on the running context.
    – Jayant Das
    Commented Aug 16, 2019 at 18:00

1 Answer 1

1

As I speculated on the comments, the best approaches might just be to either:

  1. Use the Test.isRunningTest method to check for the test context and thus bypass the .setClientCertificateName method in your code.
  2. Use a try/catch scope to catch the exception thrown when the platform tries to assign the missing certificate to the request.

The first approach works if the code is being tested in unit test contexts only (might be useful in CI/CD pipelines). The second approach is more towards real testing, in a context where you have access to an (scratch) org which doesn't have the certificate, but you are sure that other org has the correct certificate.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .