Let's say I have a class like this

 * Example of using JWTBearerTokenExchange to demonstrate issues with testing and mocks
public class JwtBearerTokenExample {

    public static String getAccessToken() {
        // Simplest example of creating a `JWTBearerTokenExchange` and trying to call `getAccessToken`.
        // This wouldn't work if it was run, but it shows that running a test will fail on `bearer.getAccessToken()`.
        Auth.JWTBearerTokenExchange bearer = new Auth.JWTBearerTokenExchange(
                new Auth.JWS(new Auth.JWT(), 'google_cloud'));

        return bearer.getAccessToken();

When I have a unit test that calls getAccessToken() an error is thrown:

System.TypeException: Methods defined as TestMethod do not support Web service callouts.

For example, here's a test class:

private class JwtBearerTokenExampleTest {

    @isTest static void getAccessTokenTest() {
        // Why doesn't this mock get used?
        // This works when mocking our other code that uses a callout and this pattern is documented at
        // https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_classes_restful_http_testing.htm
        Test.setMock(HttpCalloutMock.class, new MockHttpResponseGenerator());
        // Causes "System.TypeException: Methods defined as TestMethod do not support Web service callouts"


Is it possible to get HttpCalloutMock to work here, or do I have to resort to modifying the actual code to use a conditional with Test.isRunningTest() and have a separate code path for test?

  • Seems it is not possible at this time to test. At least my attempts to try it failed. Using web services mock did not work. I suspect that the Auth class would need to have a mock implementation within its namespace to work as setting the mock from the local namespace does not seem to invoke either the http or webservice mock. – Eric May 17 '17 at 3:05
  • @jon_wu any update on this? Did you get this to work? – Willem Mulder Sep 14 '18 at 14:34
  • I just worked around it. At the time I even opened a support case to attempt to verify there was no other way. It was waste of time as always. if (!Test.isRunningTest()) { token = bearer.getAccessToken(); } else { token = 'test-token-will-not-be-used'; } – jon_wu Sep 14 '18 at 18:46
  • Asked with Salesforce support and got given the same answer unfortunately (either use the Test.isRunningTest() check or to use the Stub API). I raised an idea for this though so hopefully it gets implemented - success.salesforce.com/ideaView?id=0873A000000EC4KQAW – Clint Jan 7 '19 at 8:10

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.