0

I created one API which is calling Flow and flow is taking data from different objects and responding back to the API class. I want to write Test class for my API Apex

1

From my perspective a unit test tests an Apex class/method in isolation. The flow is external to the Apex and isn't something to be tested together with the Apex code in a unit test. Sure, you might want to do that in an integration test, but this isn't needed to increase code coverage.

There are various ways to deal with this sort of scenario. My suggestion is to do something like the following:

  1. Make the class virtual - doing so means we can override methods as needed
  2. Separate out the code for invoking the flow into a small, virtual method
  3. In your test class write an extension of the target class that overrides the flow invocation method. This override can assert that the expected values are received for passing to the flow (using asserts).
  4. In your test class, instantiate the test version of the class and invoke it as needed, applying asserts when/if you get data back from it.

Using this approach you will not get 100% coverage (the real flow invocation code isn't exercised) but you should be able to get almost 100% coverage depending on the ratio of code not overridden vs the code that is overridden.

So, for example, you might have something like:

public virtual with sharing MyClass {
    public void doSomething(With someParameters) {
        // Does some stuff
        ...

        // Then invokes the flow
        invokeFlow(With someOtherParameters);
    }

    protected virtual void invokeFlow(With someParameterValues) {
        // Actually invokes the flow, in as few statements as possible
    }

    public static void calledFromTheFlow(...) {
        // Does some other stuff with the parameters
    }
}

In the test class you then do something like:

@IsTest
class MyClassTest {
    class TestMyClass extends MyClass {
        protected override void invokeFlow(With someParameterValues) {
            // Make sure the parameters are as expected
            System.assertEquals(expected, someParameterValues.x);
            ...
        }
    }

    @IsTest
    void testDoSomething() {
        MyClass instanceToTest = new TestMyClass();

        instanceToTest.doSomething(withTestParameters);

        // The asserts may have all been done in the test invokeFlow method
    }
}

You would separately test the calledFromTheFlow method, asserting that the required behaviour is exhibited based on values "received from the flow" (though actually just test values being passed in).

Now, note that to do this you can't write all your code as static. Avoiding static methods where possible really opens up the opportunity to write testable code.

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.