3

I want to limit the control flow during a unit test so that it does not leave the method being tested. The unit test is for a controller method, and in that method the controller creates an object and calls a method on that object.

public class MyController {
    void myMethod() {
        MyObject obj = new MyObject();
        Integer x = obj.someMethod(); 
    }
}

How do I stop someMethod() from actually being called and instead provide a test value for x?

In my research I found documentation on mocking HttpRequest objects (https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_classes_restful_http_testing_httpcalloutmock.htm), but no options for mocking other objects.

I also found the Test.isRunningTest() boolean that indicates whether a test is running, meaning that I could change my production code to:

public class MyController {
    void myMethod() {
        MyObject obj = new MyObject();

        Integer x;
        if (!Test.isRunningTest()) {
            x = obj.someMethod(); // Call method if not in test    
        } else {
            x = 1; // Test Value
        }
    }
}

But this limits the test to just one test value, and I'd like to avoid modifying production code for the sake of a test if I can help it.

So I guess the question in full is: how to provide a test value for 'x' and not call someMethod() during a test without modifying production code?

2

You can't "intercept" a call to create a new object and/or interrupt a function/constructor. Instead, try to break your code up into segments that you can adjust independently, or, if you really need to, simply make the variable have a bigger scope and make it @TestVisible:

public class MyController {
    @TestVisible transient Integer x;
    void myMethod() {
        if(x == null) {
            x = obj.someMethod();
        }
        // Do more stuff
    }
}

This way, you can then do:

MyController mc = new MyController();
mc.x = 5;
mc.myMethod();
0

You could make x a member variable.

Then you could do something like:

MyController mc = new MyController();
mc.x = 10;

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.