0

I have stubbed class with name DataUtils and class which i am testing with name DataController. Method from DataUtils that is being called in DataController is web service callout. I cannot use mock for callout and must use Stub api. So it looks like:

public class DataController {
    public method1() {
       List<String> listOfData =  new DataUtils().method2();
       return listOfData;
    }  
}

And in my DataControllerTest I have stubbed DataUtils instance. So is there any way to test method1 in DataController via Stub without modifying it? My only idea is to add something like that and then set it to stubbed DataUtils.

@TestVisible
private static DataUtils dataUtils = new DataUtils();
7
  • DataUtils.method2() looks like a static method, and static methods cannot be stubbed. That's one of the well-known limitations of the Stub API.
    – Derek F
    May 3 at 16:26
  • @DerekF thanks. its new DataUtils. my bad.
    – Terdivi
    May 3 at 16:30
  • 2
    As DerekF mentioned, you should read up on StubProvider which is similar to Java's Dynamic Proxy to an extent and allows you to substitute in an alternative implementation of non-static methods on pretty much any class as long as you have some means to inject the stub provider instance in place of the real class instance, perhaps using a dependency injection pattern in your code, or via a static singleton like you have suggested in your question.
    – Phil W
    May 3 at 16:47
  • 1
    BTW, is there a specific reason you cannot mock the callout?
    – Phil W
    May 3 at 16:55
  • @PhilW thanks, I'll read about dependency injection and try if it suits me. And i cann't mock because DataUtils in managed package, which i cann't update.
    – Terdivi
    May 3 at 16:57

0

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.