Missing Return Statement When Implementing the StubProvider Interface

656    Asked by CarolineBrown in Salesforce , Asked on Apr 23, 2021

 I am trying to implement the StubProvider Interface as Kevin Poorman does in his blog here: Kevin's Month of Testing Blog - Part 3 of 3 and on line 3 I am getting the error 'Missing return statement required return type: Object.' What could I possibly be doing wrong? Also, because we are in between releases, yes, I am in a sandbox that is running Summer '18, so it isn't (or, shouldn't be) the switch statement causing this issue. Ideas?

@isTest public class AttachmentTriggerDisabledMockStub implements System.StubProvider { public Object handleMethodCall(Object stubbedObject, String stubbedMethodName, Type returnType, List listOfParamTypes, List listOfParamNames, List<object> listOfArgs){ switch on stubbedMethodName{ when 'Disable_Attachment_AD__c', 'Disable_Attachment_AI__c', 'Disable_Attachment_AU__c'{ return false; } } } }

Why return type for the method is missing?


</object>
<object>



</object>

Answered by Caroline Brown

When a method has a non-void return type, you're responsible for ensuring that all code paths are terminated by a return statement. In this case, your switch statement prescribes the return value for a specific set of logic paths, but the compiler can't guarantee that the condition will be true. You need to provide a return statement (it can be return null;) to ensure that a return value is provided should your condition not execute. This is true regardless of the logical construct being used (it's not unique to the switch construct). To use a simple example, the following is not allowed, because the compiler cannot guarantee that a return value will be provided:

    public static Object retVal(String input) { switch on input { when 'Test' { return true; } } }

This is one way to make it legal, using when else to cover any case not already handled by a when block:

    public static Object retVal(String input) { switch on input { when 'Test' { return true; } when else { return false; } } }

That guarantees that there will be a return value, regardless of the logical path followed and regardless of the input parameter. Another way to deal with the issue is to place a simple return statement after the switch. This applies equally to other logical constructs. public static Object retVal(String input) { switch on input { when 'Test' { return true; } } return false; }



Your Answer

Interviews

Parent Categories