Help, I cannot make a test class run for the class I created below, kindly help: Apex Class global class ContactPostCode{    @InvocableMethod(label='ContactPostCodeOverWrite')      global static List&lt;FlowParametersResult&gt; cowM(List&lt;FlowParametersRequest&gt; requests){              List&lt;FlowParametersResult&gt; results = new List&lt;FlowParametersResult&gt;();                 FlowParametersResult result = new FlowParametersResult();                  for(FlowParametersRequest request : requests){              switch on request.leadPostCode{                      when ''{                  result.PostCode = request.contactPostCode;             }             when else{                                    result.PostCode = request.leadPostCode;             }                      }             result.leadPrimaryInvestmentGoal = request.leadPrimaryInvestmentGoal;            result.contactPrimaryInvestmentGoal = request.contactPrimaryInvestmentGoal;     }                  results.add(result);                return results;             }          global class FlowParametersRequest{                  @InvocableVariable         global String leadPostCode;                  @InvocableVariable         global String contactPostCode;                  @InvocableVariable         global String leadPrimaryInvestmentGoal;                  @InvocableVariable         global String contactPrimaryInvestmentGoal;                  }          global class FlowParametersResult{                  @InvocableVariable         global String PostCode;                  @InvocableVariable         global String leadPrimaryInvestmentGoal;                  @InvocableVariable         global String contactPrimaryInvestmentGoal;              }             }  ======================================================== Apex Test Class @isTest global class LeadHandlerTest{      global static void LeadHandlerTestM(){          //List&lt;FlowParametersRequest&gt; requests = new List&lt;FlowParametersRequest&gt;();          Contact contN = new Contact();         contN.FirstName = 'Test';         contN.LastName = 'Man';         contN.Email = 'test@test.com';         contN.MobilePhone = '61410777777';          contN.PostcodeTst__c = 'a0sD0000000Bxxx';         contN.Pingst__c = 'Test';         insert contN;                  Lead leadN = new Lead();         leadN.FirstName = 'Test';         leadN.LastName = 'Man';         leadN.Email = 'test@test.com';         leadN.MobilePhone = '61410777777';                 leadN.PostcodeTst__c = 'a0sD0000000Bxxx';         leadN.Pingst__c = 'Test';         insert leadN;                  List&lt;FlowParametersRequest&gt; requests = new List&lt;FlowParametersRequest&gt;();         FlowParametersRequest request = new FlowParametersRequest();         request.leadPostCode = leadN.PostcodeTst__c;         request.contactPostCode =  contN.PostcodeTst__c;         request.leadPrimaryInvestmentGoal =  leadN.Pingst__c;         request.contactPrimaryInvestmentGoal = contN.Pingst__c;                  requests.add(request);              }          global class FlowParametersRequest{         @InvocableVariable         global String leadPostCode;                  @InvocableVariable         global String contactPostCode;                  @InvocableVariable         global String leadPrimaryInvestmentGoal;                  @InvocableVariable         global String contactPrimaryInvestmentGoal;                  }                }  /* global String leadPostCode;                  @InvocableVariable         global String contactPostCode;                  @InvocableVariable         global String leadPrimaryInvestmentGoal;                  @InvocableVariable         global String contactPrimaryInvestmentGoal;   */
5058
This is a canonical question and answer developed by the community to help address common questions. If you've been directed here, or your question has been closed as a duplicate, please look through the resources here and use them to shape more specific questions. To browse all canonical questions and answers, including more unit test resources, navigate to the  tag.  This canonical question is intended to address several classes of common questions by providing a quick summary and links to comprehensive resources:   How do I start writing my first unit test?  How do I unit test this code?  I need help writing this unit test.   Salesforce Stack Exchange looks for detailed, specific questions that the community can help you with, and can't write tests on your behalf. We feel that working with the resources below can help you get started, and we encourage you to make an attempt to write your test and return to SFSE with your specific questions when you encounter challenges you can't resolve.
72121
I created a controller which looks like this  public with sharing class EventRegistrationController {      // A CONTROLLER FUNCTION     // FUNCTION RETURNS A LIST OF cSession      public List&lt;cSession&gt; getSessions() {            //DO STUFF       }     //A PUBLIC CLASS WITHIN CONTROLLER    @TestVisible public class cSession      {         public Session__c con {get; set;}         public Boolean selected {get; set;}          //This is the contructor method.          public cSession(Session__c c) {              con = c;             selected = false;         }     }  }   I need to write a test code for the controller, how can I create a list of cSession and call getSession function?
3150
What is the best practice for writing apex test classes where you have multiple callouts? My Test Class would then be testing the secondCallout method which happens to also call a firstCallout method that has a callout in itself. My question is, what is the appropriate way to be able to run the mock test for both methods? Main Class public class myclass {    public static String firstCallOut() {         HttpRequest req = new HttpRequest ();         HttpResponse res = new HttpResponse();         req.setMethod('POST');         //code snippets only          return res.getBody().    }     public static void secondCallOut() {        String resultFromFirstCallout = firstCallOut();          HttpRequest req = new HttpRequest ();         req.setMethod('POST');         req.setBody(resultFromFirstCallout);         //code snippets only      }   }  Mock Class public with sharing class MyMockclass implements HttpCalloutMock {          protected Integer code;     protected String status;     protected String body;     protected Map&lt;String, String&gt; responseHeaders;     public MyMockclass (Integer code, String status, String body, Map&lt;String, String&gt; responseHeaders) {       this.code = code;       this.status = status;       this.body = body;       this.responseHeaders = responseHeaders;     }      public HTTPResponse respond(HTTPRequest request) {         // Create a fake response         HttpResponse response = new HttpResponse();         for (String key : this.responseHeaders.keySet()) {           response.setHeader(key, this.responseHeaders.get(key));         }         response.setBody(this.body);         response.setStatusCode(this.code);         response.setStatus(this.status);         return response;       }  }  Test Class @isTest(seeAllData=false) public class myclassTest{     static testMethod void myTestMethod(){               Map&lt;String, String&gt; responseHeader = new Map&lt;String, String&gt;();             responseHeader .put('Content-Type','application/json');              MyMockclass mock= new MyMockclass (                 200,                 'success',                 'Succesful',                 responseHeader              );             Test.setMock(HttpCalloutMock.class, mock);               Test.startTest();             myclass.secondCallOut();             Test.stopTest();         }
77237
I am unable to cover the following class get set method. Need help in creating test class  public class Aresult{      public class Parent {         public String type {get; set;}         public String id {get; set;}         public String sequence_id {get; set;}         public String etag {get; set;}         public String name {get; set;}     } }   Please suggest  @isTest  public class CirriusGetItemsResultTest {     public static void myUnitTest(){         Aresult.parent a = new Aresult.parent();         a.type='hello';         a.id='hello';         a.sequence_id ='hello';         a.etag ='hello';         a.name ='hello';     } }
16290
This is a canonical question and answer developed by the community to help address common questions. If you've been directed here, or your question has been closed as a duplicate, please look through the resources here and use them to shape more specific questions. To browse all canonical questions and answers, navigate to the  tag. This question and answer is owned by the community! If you can improve it and make it more useful, you're welcome to edit it. I am building a trigger, a unit test, or other Apex code. I'm working with sObject records, and trying to access related record information. For example, I might have a structure like this: Account a = new Account(Name = 'Test'); insert a;  Opportunity o = new Opportunity(Name = 'Donation', AccountId = a.Id); insert o;  System.assertEquals(o.Account.Name, 'Test', 'Correct Account associated'); // Assertion fails!  Or, in a trigger, I might be aiming for something like this: trigger ContactTrigger on Contact (after insert) {     for (Contact c : Trigger.new) {         if (c.Account.Name == 'Test') {             // Take some action here         }      } }  Why doesn't this work? Why am I getting null values, or NullPointerExceptions?
15426
How do I write a unit-test / test class for a trigger?  What are my options?   Inline with the trigger?  New Class?
93772
below is my code Created a wrapper class like below  public class ResponseWrapper{     public list&lt;Account&gt; lstaccounts;     public boolean isError ;     public string errorCode;     public integer statusCode;        public ResponseWrapper(){          lstaccounts = new list&lt;Account&gt;();          isError= false;     }  }   and returning the wrapper class in the Httpget method  @RestResource(urlMapping='/accounts/*') global with sharing class AccountRestService { @HttpGet global static ResponseWrapper getAccounts() {     ResponseWrapper resWrap = new ResponseWrapper();     List&lt;Account&gt; accounts;      try {         accounts = [SELECT Id, Name FROM Account];         res.lstaccounts = accounts;     } catch (Exception e) {         RestResponse res = RestContext.response;         resWrap.isError = true;         res.responseBody = Blob.valueOf(e.getMessage()) = resWrap.errorCode;         res.statusCode = 500 = resWrap.statusCode;     }      return resWrap;   } }   but its throwing the Error message  Error: Compile Error: global methods do not support return type of ResponseWrapper at line 4 column 31
109516
I'm trying to use the HTTP Callout methods provided in Apex to  1. Get a token from Marketo 2. Use this token to create three leads in Marketo using the REST API  However, it doesn't seem to be working. I have never coded something like this before, so I expect that I probably made some very embarrassing and obvious mistakes, but I've been able to find very little documentation on this, so I'm starting from basically scratch and the REST API documentation. Anyways, here's the two classes I've been using to attempt to do this:  Class 1:  global class MakeCallouts {       static String testCallout() {          HttpResponse res = CalloutClass.getInfoFromExternalService();         String contentType = res.getHeader('Content-Type');         System.assert(contentType == 'application/json');         System.assertEquals(200, res.getStatusCode());      //getting the accesstoken       String getToken;     String answer = res.getBody();     System.debug(answer);  JSONParser parser = JSON.createParser(answer); while (parser.nextToken() != null) {     if ((parser.getCurrentToken() == JSONToken.FIELD_NAME)){         String fieldName = parser.getText();         parser.nextToken();         if(fieldName == 'access_token') {            getToken = parser.getText();               }  } } System.debug(getToken);           HttpResponse res2 = CalloutClass.getInfoFromExternalService2(getToken);           String contentType2 = res2.getHeader('Content-Type');         System.assert(contentType2 == 'application/json');         System.assertEquals(200, res2.getStatusCode());          System.debug(res2.getBody());         return res2.getBody();     } }   Class 2:  public class CalloutClass {  public static HttpResponse getInfoFromExternalService () {     // Instantiate a new http object     Http h = new Http();       // Instantiate a new HTTP request, specify the method (GET) as well as the endpoint     HttpRequest req = new HttpRequest();     req.setEndpoint('https://XXX-rlu-923.mktorest.com/identity/oauth/token?grant_type=client_credentials&amp;client_id=XXXX&amp;client_secret=XXXX');     req.setMethod('GET');      // Send the request, and return a response     HttpResponse res = h.send(req);     return res;  }   public static HttpResponse getInfoFromExternalService2 (String getToken) {     // Instantiate a new http object     Http h2 = new Http();       // Instantiate a new HTTP request, specify the method (POST) as well as the endpoint     HttpRequest req2 = new HttpRequest();     req2.setHeader('Content-Type','application/json');      req2.setMethod('POST');     req2.setEndpoint('https://XXXX.mktorest.com/rest/v1/leads.json?access_token='+getToken);     req2.setBody('{"action":"createOnly","input":[{"email":"kjashaedd-1@klooblept.com","firstName":"Kataldar-1","postalCode":"04828"},{"email":"kjashaedd-2@klooblept.com","firstName":"Kataldar-2","postalCode":"04828"},{"email":"kjashaedd-3@klooblept.com","firstName":"Kataldar-3","postalCode":"04828"}]}}');      // Send the request, and return a response     HttpResponse res2 = h2.send(req2);     return res2;  }    }   The MakeCallouts class is triggered when a Lead is created (this is entirely for testing purposes. I'm going to change the API call after I get this to work. But it's pretty obvious that the call is working when I see three new leads appear in my database, so it's a good test).
22098
I'm deploying an apex class and Test class which is running successfully and covering 84% test coverage in sandbox however when deploying it in Prod, I'm running in to below issue. I have included Static Resource in the changeset. Any ideas what is wrong with it? The Static resource consist of a CSV file that includes User data (Name, email, Username , lastlogindate). istest public class TestScheduleInactiveUser {     @istest static void ScheduleInactiveUser(){              List&lt;sObject&gt; ls = Test.loadData(User.sObjectType, 'UserLoadTest');                          Test.startTest();             ScheduleInactiveUser fc=new ScheduleInactiveUser();             Database.executeBatch(fc);         Test.stopTest();              } }   Error: System.SObjectException: ORA-20001: ORA-06512: at &quot;DOC.CPROFILE&quot;, line 1128 ORA-01403: no data found ORA-06512: at &quot;DOC.CPROFILE&quot;, line 2940 ORA-06512: at line 1 SQLException while executing plsql statement: {?=call cProfile.get_user_type(?)}(00eP0000000bIq5)  Stack Trace:  Class.System.Test.loadData: line 53, column 1 Class.TestScheduleInactiveUser.ScheduleInactiveUser: line 5, column 1
90240
I have the below code:  public class CallOutForGet {      HttpRequest request=new Httprequest(); http http=new http(); request.setEndPoint('https://th-apex-http-callout.herokuapp.com/animals'); request.setmethod('GET');  HttpResponse response=http.send(request);  if(response.getStatusCode()==200){      Map&lt;String,Object&gt; results= (Map&lt;String,Object&gt;)JSON.deserializeUntyped(response.getBody());      List&lt;object&gt; animals=(List&lt;object&gt;)results.get('animals');     System.debug('Received Animals************');     for(object anim:animals){         System.debug(anim);     } }  }   This error at line -  request.setEndPoint('https://th-apex-http-callout.herokuapp.com/animals');  says expecting right parenthesis.
115021
Ideally, I'd like to write a unit test to help me "dummy check" for unexpected effects of the upcoming guest user sharing setting changes.  We'd had some controller/trigger code "gracefully handling" data it couldn't see thanks to the new sharing restrictions ... which resulted in simply "not doing" some work that it was supposed to do, which from a business process perspective isn't "graceful" at all (it was an important automation for downstream processes).  I'd like to write up a unit test with some system.assert statements validating that "data still goes where it's supposed to" when the "submit" button a public-facing Visualforce page of a community is clicked.  Unfortunately, I can't seem to make the "submit" button on a Controller for a public-facing Visualforce page work in the context of a unit test because the record whose creation it results in doesn't get its corresponding "sharing setting" record created in time for the execution context to pick it up.  I did a little proof of concept here ...  @isTest public class TestClass {      private static Id guestProfileId = Util.getProfileIdByName('Public Facing Portal Profile');     private static User guestUser;     private static Id portalGroupId = [SELECT Id FROM Group WHERE Name = 'Public_Portal' LIMIT 1][0].Id;      private static Custom_Object__c co;       private static testMethod void runTest() {         createCO();         Test.startTest();         // Note that putting createCO() inside the test and doesGuestSharingRuleExistForCO() doesn't help.         // That's what I was afraid of.         try {             doesGuestSharingRuleExistForCO(co.Id);         }         catch (Util.DeveloperException e) {             System.assert(FALSE, e.getMessage());         }         Test.stopTest();     }       private static void cacheUsers() {         guestUser = [SELECT Id FROM User WHERE profileid = :guestProfileId AND IsActive = TRUE LIMIT 1][0];     }      private static void createCO() {         co = new Custom_Object__c();         INSERT co;     }      private static void doesGuestSharingRuleExistForCO(Id coId) {         List&lt;SObject&gt; existingSharingRulesOnCO = [             SELECT Id FROM Custom_Object__share             WHERE RowCause = 'GuestRule' AND AccessLevel = 'Read' AND ParentId = :coId AND UserOrGroupId = :portalGroupId LIMIT 1         ];         if ( existingSharingRulesOnCO.isEmpty() ) { throw new Util.DeveloperException('Guest User sharing is not on for this custom object ID'); }     }      private static Boolean isCOSharingFlippedOnAtAll(){         String lookingFor = 'Custom_Object__Share';         for (Schema.SObjectType sObjectType : Schema.getGlobalDescribe().values() ) {             String sobjName = String.valueOf(sObjectType);             if (sobjName.contains(lookingFor) ) { return TRUE; }         }         return FALSE;     }  }   Am I just out of luck?  Is there no way to properly unit-test the effects (to automations relying upon "guest user" sharing settings when running as "guest user") of simulating the insertion of records into my database from a Visualforce page, due to not being able to separate out "execution context" enough and "wait" for the sharing rule record for the new record to come into existence?
494
i have created a schedulable class which has to trigger a batch job. The run method for the batch class will get list of data to process from a webservice callout. Now, i got the exception below. Any suggestions please.     System.CalloutException: Callout from scheduled Apex not supported.   global class scheduledDeltaBatchable implements Schedulable {    global void execute(SchedulableContext sc) {     ID batchprocessid = BatchUpsertSAPCustomerMasterBPSync.run(SAPServices.GetSAPCustomerMasterBPSync('Delta'));    } }
92053
I would know how to cover, with the test class, the catch block in my apex trigger:  APEX TRIGGER:      try{               update olis_updated;         } catch (DMLException e){                 for (OpportunityLineItem o :olis){                        o.addError('There was a problem setting Product_Category__c ');                }           }    TEST CLASS:  I've tried like following, but it doesn't work   // GENERATE EXECEPTION                test.startTest();                  lineItem1.id=lineItem2.id;                  update lineItem1;                test.stopTest();   How can i generate an exeception? Thanks in advantage for any advice.  BR
20064
I have written below Wrapper class.  global class BI_VA_AutomationWrapper {      global class BI_VA_AutomationRequest {      webservice String userName;     webservice String emailId;     webservice String buinessUnit;     webservice String orgName;     webservice String country;     webservice String environment;     webservice String myShopNumber;     webservice String BidsId;//for testing     webservice String Type; //for testing  }  global class BI_VA_AutomationResponse {      webservice String responseStatus;     webservice String myShopNumber;     //webservice list&lt;Error&gt; errorMessages;     webservice String  errorMessages;//for testing   } global class BI_VA_Error {      webservice String type;     webservice String message;    }}   And test class is,  @isTest public class BI_VA_AutomationWrapperTestClass  { public static testMethod void unitTest(){      BI_VA_AutomationWrapper.BI_VA_AutomationRequest wrap= new BI_VA_AutomationWrapper.BI_VA_AutomationRequest();        wrap.userName='Test@test.com';     wrap.emailId='Test@test11.com';     wrap.buinessUnit='AH';     wrap.orgName='ORD';     wrap.country='US';     wrap.environment='QA';     wrap.myShopNumber='123456789';     wrap.BidsId='123';     wrap.Type='ResetPassword';              BI_VA_AutomationWrapper.BI_VA_AutomationResponse res= new BI_VA_AutomationWrapper.BI_VA_AutomationResponse();     res.responseStatus = 'Success';     res.myShopNumber = '987654321';     res.errorMessages = 'Test error';      BI_VA_AutomationWrapper.BI_VA_Error error = new BI_VA_AutomationWrapper.BI_VA_Error();     error.type = 'Test';     error.message = 'Test';  }}   Code coverage is 0% only.
56441
I am currently programming a trigger on Opportunities.   I created a test class for this and in my Sandbox I created an account, contact and opportunity. When I try to reference them   Opportunity Opp = [SELECT id from Opportunity where name = 'Test1'];    and then start my   Test.startTest();         Opp.StageName = 'PO in (100%)';          update Opp;         Test.stopTest();   It just errors and shows that Opp returns 0 rows. However when I paste my first bit of code in 'Execute Anonymous' it returns a row and the correct info.   Does this mean I have to create an account, contact, quote and all necessary fields in my test class?
109534
I am trying to write a test class.  My Apex class has the following constructor:  public NController(ApexPages.StandardController controller) {      cas =  (Case) controller.getRecord();     csId = cas.Id;     owner = cas.OwnerId;      N_SSettings__c nhdsms = N_SSettings__c.getValues('Int');     rate=nhdsms.Rate_Code__c;     accId=nhdsms.Acc_Id__c;  }   Here N_SSettings__c is a custom settings which has two fields Rate_Code__c and Acc_Id__c. It has a record called 'Int' with both Rate_Code__c and Acc_Id__c field values populated.  I am using the following test class method:  @isTest public class NHSsendSMSController_Test {     public static testMethod void NHSsendSMSControllerTest()     {         Case caseObj = new Case();         insert caseObj;         ApexPages.StandardController sc = new ApexPages.standardController(caseObj);         NController nControllerObj = new NController(sc);         nControllerObj.methodName();     } }   When I run the test method, it is throwing a null pointer exception on the line :  rate = nhdsms.Rate_Code__c;   The custom setting is definitely present with the required values of both the fields of Int.
55978
I have a Process Builder flow set up and I am running some tests around the InvocableMethod Apex code. The tests pass fine in my staging and production environments. Yet, when I try to deploy to production, I get a strange error.  CANNOT_EXECUTE_FLOW_TRIGGER, The record couldn’t be saved because it failed to trigger a flow.  Thankfully I received a somewhat more informative error email.  UPSERT FAILED ---  ERRORS :  (CANNOT_EXECUTE_FLOW_TRIGGER) The record couldn’t be saved because it failed to trigger a flow. common.exception.AssertionException: ORA-20070: Cannot read from apex_class and apex_trigger while running tests ---  for SFDC record with ID : null,  Unfortunately, the deployment has nothing to do with the flow and it is unclear why it is failing. What is the root cause of this error and how can I fix it? EDIT: I found out this is a . The other claimed workaround is to deploy via the Metadata API. UPDATE: Because I was subscribed to the Known Issue, I received the following confirmation this issue is resolved.  We are pleased to notify you that the following Known Issue has been resolved: Executing an InvocableMethod during an apex test run from a change set can cause Errors. Thank you for being patient while we worked to address this issue. Please feel free to reach out to Customer Support if you have further questions. Sincerely, Salesforce Success Team