1

In my Apex code, I already have an external HTTP callout.

Now, I aim to use a boolean flag in production code to control whether do real HTTP callout or read a static JSON from mdt records (i.e. a human can update the mockup data in mdm record to mimic the returning data from the external API).

The mockup works as follows: instead of making a real callout, the Apex can read a static JSON value stored in a custom metadata type record. I toggle the mockup on/off with a boolean flag in a custom setting.

In the production code:

if (useMockup()) { // check the boolean flag in custom setting;
  return getMockUpHttpResponse(); // the data is retrieved from custom metadata type record;
} else{
  // do real http callout;
}

My challenge is how to unit test this logic. Custom metadata types are exposed to Apex code, and the record in the org determines whether the unit test succeeds or fails, which conflicts with the concept of unit testing.

Thanks for your help!

1 Answer 1

0

Read up about test.isrunningtest() and test.setmock()? I like using setmock because it's the caller (the unit test) that injects the dummy result generator, you don't put "if test then..." logic in your "pure" code.

And if you decide to use it -you can hardcode the dummy result in the mock class or fetch from custom meta?

Sign up to request clarification or add additional context in comments.

2 Comments

Sorry that my original post doesn't mention clearly, I have updated it. This mockup is mean to be used by people rather than Apex test code, so I perceive that test.isrunningtest() and test.setmock() doesn't help in this scenario.
Ha, got it. I'd ringfence the metadata used in tests by adding a checkbox field and WHERE IsTest__c =:test.isrunningtest(). Maybe even filter them by that checkbox in listviews to reduce risk of users messing them up. Or you could write tests that use real "setmock" and "real callout" path to check error/success scenarios. And 1 test that just fetched from custom meta bit asserts "something came back" without relying on anything users could have changed

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.