+ Start a Discussion
Sammy ShkSammy Shk 

Test class for HTTP post REST API

Hello I'm trying to write a test class for Rest API post Method which i wrote, need help in writing test method. This gives me System.DmlException: Update failed. First exception on row 0; first error: MISSING_ARGUMENT, Id not specified in an update call:". Please help
trigger RadarFirst on Patient_Satisfaction__c (after update) {
for (Patient_Satisfaction__c cc : Trigger.new){
if(cc.Patient_Relation__c!= Trigger.oldMap.get(cc.id).Patient_Relation__c && cc.Patient_Relation__c != null) {
      if(cc.Patient_Relation__c.contains('Referred to Privacy Office')){
      RadarUpdate.postcallout(cc.id);
      }
  }
}
}
 
public class RadarUpdate {
    @future (callout=true)
	public static void postcallout(string Id) { 
	Patient_Satisfaction__c c = [select id, Name, Reporter_Phone__c,Reporter_First_Name__c,Reporter_Last_Name__c, Reporter_Email__c,
    Description_of_Feedback__c from Patient_Satisfaction__c where Patient_Relation__c ='Referred to Privacy Office' order by lastmodifiedDate desc limit 1];
    JSONGenerator gen = JSON.createGenerator(true);
	gen.writeStartObject();
	gen.writeObjectField('name', c.Name);
	gen.writeObjectField('incident_group_id', 7387);
    gen.writeObjectField('description',c.Description_of_Feedback__c);
	gen.writeFieldName('submitted_by');
	gen.writeStartObject();
	gen.writeStringField('given_name',c.Reporter_First_Name__c);
	gen.writeStringField('surname', c.Reporter_Last_Name__c);
	gen.writeStringField('phone',c.Reporter_Phone__c);
    gen.writeStringField('email',c.Reporter_Email__c);
	gen.writeEndObject();
	String jsonS = gen.getAsString(); 
	System.debug('jsonMaterials'+jsonS);
    Http http = new Http();
	HttpRequest request = new HttpRequest();
	request.setEndpoint('https://api.radarfirst.com/incidents');
	request.setMethod('POST');
	request.setHeader('Content-Type','application/json;charset=UTF-8');
	request.setHeader('User-agent', 'Salesforce-integration-client');
	request.setHeader('Authorization','Bearer 123');
    request.setBody(jsonS);
	// Set the body as a JSON object
	HttpResponse response = http.send(request);
	if (response.getStatusCode() != 201) {
    System.debug('The status code returned was not expected: ' +
        response.getStatusCode() + ' ' + response.getStatus());
	} else {
    System.debug(response.getBody());
	}
    }
}
@isTest
public class RadarUpdateTest{

    static testMethod void  postcalloutTest(){
        Account ac = new Account();
        ac.Name= 'Test';
        insert ac;
        
        Contact con= new Contact();
        con.AccountId= ac.Id;
        con.FirstName ='First Name';
        con.LastName = 'Test Contact';
        con.Phone= '7896541233';
        con.Email= 'Test@123.com';
        con.RUSH_Email__c= 'Test@123.com';
        insert con;
         		
        Patient_Satisfaction__c Pr = new Patient_Satisfaction__c();
        Pr.Primary_Campus__c = 'a1pP0000001lfaKIAQ';
        Pr.Primary_Facility__c= 'a1pP00000022FLRIA2';
        Pr.Primary_Location__c= 'a1pP00000022FLcIAM';
        Pr.Reporter__c=con.Id;
        Pr.Reporter_Phone__c=con.Id;
        Pr.Reporter_Email__c= 'Test@123.com';
        Pr.Description_of_Feedback__c= 'Testing Privacy office';
        Pr.Patient_Relation__c = 'Referred to Privacy Office';
        
     update Pr;
  	 RadarUpdate reqst=new RadarUpdate();
   	 String JsonMsg=JSON.serialize(reqst);
     Test.startTest();

    RestRequest req = new RestRequest(); 
    RestResponse res = new RestResponse();

    req.requestURI = '/services/apexrest/DemoUrl';  //Request URL
    req.httpMethod = 'POST';//HTTP Request Type
    req.requestBody = Blob.valueof(JsonMsg);
    RestContext.request = req;
    RestContext.response= res;
    RadarUpdate.postcallout(Pr.Id);
  
    update Pr;
    Test.stopTest();

   }
}

 
Best Answer chosen by Sammy Shk
Derrick AbbeyDerrick Abbey
Hi Sammy,

The issue is with line 28 of your test class.  You're trying to perform an update on a record that doesn't exist in the DB yet.  Unit tests don't normally have visibility to data in the database.  So I'd suggest that you create the Patient_Satisfaction__c record first, then perform an update on the Patient_Relation__c field.

That being said, I noticed a couple of other issues you're probably going to run into with this testmethod.
  1. You're hard-coding Ids in 3 of the fields on the Patient_Satisfaction__c object.  This will cause problems because, as I mentioned, test classes don't usually have access to actual data.  You have two options for addressing this:
    1. Create test records for each of those lookups and use those Ids from the test records (best practice)
    2. Use @isTest(SeeAllData=true) 
  2. The second issue you'll likely run into is that you're not allowed to perform callouts in unit tests.  In order to test callouts, you have to create a mock callout and use that.  Instructions for doing so are here: Testing HTTP Callouts (https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_classes_restful_http_testing.htm?search_text=mock)

All Answers

Derrick AbbeyDerrick Abbey
Hi Sammy,

The issue is with line 28 of your test class.  You're trying to perform an update on a record that doesn't exist in the DB yet.  Unit tests don't normally have visibility to data in the database.  So I'd suggest that you create the Patient_Satisfaction__c record first, then perform an update on the Patient_Relation__c field.

That being said, I noticed a couple of other issues you're probably going to run into with this testmethod.
  1. You're hard-coding Ids in 3 of the fields on the Patient_Satisfaction__c object.  This will cause problems because, as I mentioned, test classes don't usually have access to actual data.  You have two options for addressing this:
    1. Create test records for each of those lookups and use those Ids from the test records (best practice)
    2. Use @isTest(SeeAllData=true) 
  2. The second issue you'll likely run into is that you're not allowed to perform callouts in unit tests.  In order to test callouts, you have to create a mock callout and use that.  Instructions for doing so are here: Testing HTTP Callouts (https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_classes_restful_http_testing.htm?search_text=mock)
This was selected as the best answer
manish arora 26manish arora 26
Hi Dude 
i want to make this website as web apk can you make like this good interface Download white Hill Music presenting Tik Tok Most viral song Himachal wali (https://mp3.getlyricsname.com/himachal-wali-song-download-pagalworld/)/हिमाचल वाली song MP3 download latest version full song by Manavgeet Gill. Music composed by Hakeem. download mp3 Song from https://mp3.getlyricsname.com/