You need to sign in to do that
Don't have an account?
KrForce
Need help in writing the test class for Salesforce REST class
Here is REST handler.
@RestResource(urlMapping='/UpdateContact/*')
global with sharing class REST_ParticipantHandler {
@HttpPost
global static void updateParticipant() {
//rest context variable initialization.
RestRequest req = RestContext.request;
RestResponse res = RestContext.response;
//utill class returns fieldmap from the custom setings
Map<String,String> FieldMap=util.getFieldMap();
Map<String,String> FieldTypeMap=util.getFieldTypeMap();
Map<String, Object> jsonBodyMap = (Map<String, Object>)JSON.deserializeUntyped(req.requestBody.toString());
Blob body = req.requestBody;
String bodyString = body.toString();
Wrapclass deserializedinput = (Wrapclass)JSON.deserialize(bodyString, Wrapclass.class);
Map<String, Object> jsonBodyMapLcase = new Map<String, Object>();
string qFields=String.join(FieldMap.values(), ', ');
string uNum='';
String sf_jsonResponse = '';
//converting jSON body map keys into lowercase to handle casesensitity issues.
for( string s1:jsonBodyMap.keySet()){
jsonBodyMapLcase.put(s1.toLowerCase(),String.valueOf((String)jsonBodyMap.get(s1)));
system.debug(LoggingLevel.error,'jsonBodyMap#'+s1+'='+String.valueOf((String)jsonBodyMap.get(s1)));
}
//getting the userNum from Jsonbody to instantiate corresponding participant record.
if(!string.IsBlank((String)jsonBodyMap.get('userNum'))){
uNum = !string.IsBlank((String)jsonBodyMap.get('userNum'))?String.valueOf((String)jsonBodyMap.get('userNum')):'';
}
system.debug(LoggingLevel.error,'uNum#'+uNum);
system.debug(LoggingLevel.error,'jsonBodyMap#'+jsonBodyMap);
// No userNum parameter was found; return status 400
if(uNum == null) {
res.statusCode = 400;
sf_jsonResponse = '{"response": {"status": "Failure", "message": "MissingRequiredQueryParameter userNum"}}';
res.responseBody = blob.valueOf(sf_jsonResponse);
return;
}
//Dynamic query to query the object dynamically with all the fields.
string query ='SELECT ' + qFields
+ ' FROM contact'
+ ' WHERE user_num__c = \'' + String.escapeSingleQuotes(uNum) + '\''
+ ' LIMIT 1';
system.debug(LoggingLevel.error,'query#'+query);
List<Contact> parts=Database.query(query);
// No Participants with matching userNum
if( parts.size()<=0) {
res.statusCode = 400;
sf_jsonResponse = '{"response": {"status": "Failure", "message": "No matching Participant record:'+uNum+' ' +'found with this userNum"}}';
res.responseBody = blob.valueOf(sf_jsonResponse);
return;
}
//participant Instance
contact p=parts.get(0);
for(String pfield:FieldMap.keySet()){
if(!string.IsBlank((String)jsonBodyMapLcase.get(pfield))){
if('Text'==FieldTypeMap.get(pfield)) {
p.put(FieldMap.get(pfield),String.valueOf((String)jsonBodyMapLcase.get(pfield)));}
else if('Currency'==FieldTypeMap.get(pfield)){
p.put(FieldMap.get(pfield),Decimal.valueOf((String)jsonBodyMapLcase.get(pfield)));}
else if('Number'==FieldTypeMap.get(pfield)) {
p.put(FieldMap.get(pfield),Integer.valueOf((String)jsonBodyMapLcase.get(pfield)));}
else if('Date'==FieldTypeMap.get(pfield)) {
system.debug(LoggingLevel.error,'Field=' + FieldMap.get(pfield));
//Data coming as a string value with '-' seprator and salesfore wont accept the string to date field. needs to convert string to salesforce date formate.
string sDate=string.valueOf((String)jsonBodyMapLcase.get(pfield));
system.debug(LoggingLevel.error,'sDate**=' + sDate);
//date d =util.getDateSfFormate(sdate);
String[] myDateOnly = sDate.split(' ');
String[] strDate = myDateOnly[0].split('-');
Integer myIntYear = integer.valueOf(strDate[0]);
Integer myIntMonth = integer.valueOf(strDate[1]);
Integer myIntDate = integer.valueOf(strDate[2]);
Date dt= Date.newInstance(myIntYear, myIntMonth, myIntDate);
system.debug(LoggingLevel.error,'dt**=' + dt);
p.put(FieldMap.get(pfield),dt);}
else if('Checkbox'==FieldTypeMap.get(pfield)){
if(String.valueOf((String)jsonBodyMapLcase.get(pfield))=='1'){
p.put(FieldMap.get(pfield),True);}
else {
p.put(FieldMap.get(pfield),False);}
}
}
else{
p.put(FieldMap.get(pfield),null);}
}
system.debug(LoggingLevel.error,'updated Participant=' + p);
try {
res.statusCode = 200;
update p;
sf_jsonResponse = '{"response": {"status": "Sucess", "message": "Participant record:'+uNum +' ' +'is updated in Salesforce"}}';
res.responseBody = blob.valueOf(sf_jsonResponse);
return;
} catch ( Exception ex ) {
res.statusCode = 500;
sf_jsonResponse = '{"response": {"status": "Failure", "message": "Participant record:'+uNum +' '+ ex + '"}}';
res.responseBody = blob.valueOf(sf_jsonResponse);
return;
}
}
global class Wrapclass {
public String status;
public String responseBody;
}
}
Here is my Test class..
@isTest(seeAllData=false)
Public class Test_RESTParticipantHandler {
public static testMethod void testdoPost() {
System.RestContext.request = new RestRequest();
System.RestContext.response = new RestResponse();
Account a = new Account(Name = 'Test', RK_ID__c='106',PR_FE_Branded__c= true);
insert a;
String orgId=a.id;
Contact c = new Contact();
c.firstname = 'Wain';
c.lastname = 'R';
c.AccountId = orgId;
c.email = 'Wain@test.com';
c.phone = '6884382997';
c.mailingstreet = '123 Test Ave';
c.mailingcity = 'Somewhere';
c.mailingstate = 'MA';
c.mailingPostalCode = '87945';
c.mailingcountry = 'US';
c.User_Num__c='1234567';
insert(c);
RestRequest req = new RestRequest();
RestResponse res = new RestResponse();
REST_ParticipantHandler.Wrapclass reqst=new REST_ParticipantHandler.Wrapclass();
reqst.status= 'Success';
reqst.responseBody ='{"state":"CA","riskTolerance":"Typical for your age","retirementAge":"70",alPortfolio":"65627.50","phoneContactPreference":"SEC Required Only","email":"","homePhone":"5555555555","title":"","mailingAddress":"13630 SE 231ST ST","userNum":"13328911","lastInitial":"R","city":"Sunnyvale","zip":"94086","foreignResident":"0","workPhone":"4084986934","otherPhone":"5555555555",","isFeBrand":"1","primaryAccountPlan":"Voluntary Investment Plan (VIP)","convertedFromUserNum":"","convertedToUserNum":"","countryCode":"US"}';
String JsonMsg=JSON.serialize(reqst);
req.requestURI ='/services/apexrest/UpdateParticipant';
req.httpMethod = 'POST';
req.requestBody = Blob.valueof(JsonMsg);
RestContext.response= res;
RestContext.request = req;
REST_ParticipantHandler.UpdateParticipant();
//System.assertEquals('true', results.success);
//System.assertEquals(10, results.records.size());
}
}
*****************************************************************
Im getting an error "System.QueryException: unexpected token: 'FROM'"
**********************************************************************
@RestResource(urlMapping='/UpdateContact/*')
global with sharing class REST_ParticipantHandler {
@HttpPost
global static void updateParticipant() {
//rest context variable initialization.
RestRequest req = RestContext.request;
RestResponse res = RestContext.response;
//utill class returns fieldmap from the custom setings
Map<String,String> FieldMap=util.getFieldMap();
Map<String,String> FieldTypeMap=util.getFieldTypeMap();
Map<String, Object> jsonBodyMap = (Map<String, Object>)JSON.deserializeUntyped(req.requestBody.toString());
Blob body = req.requestBody;
String bodyString = body.toString();
Wrapclass deserializedinput = (Wrapclass)JSON.deserialize(bodyString, Wrapclass.class);
Map<String, Object> jsonBodyMapLcase = new Map<String, Object>();
string qFields=String.join(FieldMap.values(), ', ');
string uNum='';
String sf_jsonResponse = '';
//converting jSON body map keys into lowercase to handle casesensitity issues.
for( string s1:jsonBodyMap.keySet()){
jsonBodyMapLcase.put(s1.toLowerCase(),String.valueOf((String)jsonBodyMap.get(s1)));
system.debug(LoggingLevel.error,'jsonBodyMap#'+s1+'='+String.valueOf((String)jsonBodyMap.get(s1)));
}
//getting the userNum from Jsonbody to instantiate corresponding participant record.
if(!string.IsBlank((String)jsonBodyMap.get('userNum'))){
uNum = !string.IsBlank((String)jsonBodyMap.get('userNum'))?String.valueOf((String)jsonBodyMap.get('userNum')):'';
}
system.debug(LoggingLevel.error,'uNum#'+uNum);
system.debug(LoggingLevel.error,'jsonBodyMap#'+jsonBodyMap);
// No userNum parameter was found; return status 400
if(uNum == null) {
res.statusCode = 400;
sf_jsonResponse = '{"response": {"status": "Failure", "message": "MissingRequiredQueryParameter userNum"}}';
res.responseBody = blob.valueOf(sf_jsonResponse);
return;
}
//Dynamic query to query the object dynamically with all the fields.
string query ='SELECT ' + qFields
+ ' FROM contact'
+ ' WHERE user_num__c = \'' + String.escapeSingleQuotes(uNum) + '\''
+ ' LIMIT 1';
system.debug(LoggingLevel.error,'query#'+query);
List<Contact> parts=Database.query(query);
// No Participants with matching userNum
if( parts.size()<=0) {
res.statusCode = 400;
sf_jsonResponse = '{"response": {"status": "Failure", "message": "No matching Participant record:'+uNum+' ' +'found with this userNum"}}';
res.responseBody = blob.valueOf(sf_jsonResponse);
return;
}
//participant Instance
contact p=parts.get(0);
for(String pfield:FieldMap.keySet()){
if(!string.IsBlank((String)jsonBodyMapLcase.get(pfield))){
if('Text'==FieldTypeMap.get(pfield)) {
p.put(FieldMap.get(pfield),String.valueOf((String)jsonBodyMapLcase.get(pfield)));}
else if('Currency'==FieldTypeMap.get(pfield)){
p.put(FieldMap.get(pfield),Decimal.valueOf((String)jsonBodyMapLcase.get(pfield)));}
else if('Number'==FieldTypeMap.get(pfield)) {
p.put(FieldMap.get(pfield),Integer.valueOf((String)jsonBodyMapLcase.get(pfield)));}
else if('Date'==FieldTypeMap.get(pfield)) {
system.debug(LoggingLevel.error,'Field=' + FieldMap.get(pfield));
//Data coming as a string value with '-' seprator and salesfore wont accept the string to date field. needs to convert string to salesforce date formate.
string sDate=string.valueOf((String)jsonBodyMapLcase.get(pfield));
system.debug(LoggingLevel.error,'sDate**=' + sDate);
//date d =util.getDateSfFormate(sdate);
String[] myDateOnly = sDate.split(' ');
String[] strDate = myDateOnly[0].split('-');
Integer myIntYear = integer.valueOf(strDate[0]);
Integer myIntMonth = integer.valueOf(strDate[1]);
Integer myIntDate = integer.valueOf(strDate[2]);
Date dt= Date.newInstance(myIntYear, myIntMonth, myIntDate);
system.debug(LoggingLevel.error,'dt**=' + dt);
p.put(FieldMap.get(pfield),dt);}
else if('Checkbox'==FieldTypeMap.get(pfield)){
if(String.valueOf((String)jsonBodyMapLcase.get(pfield))=='1'){
p.put(FieldMap.get(pfield),True);}
else {
p.put(FieldMap.get(pfield),False);}
}
}
else{
p.put(FieldMap.get(pfield),null);}
}
system.debug(LoggingLevel.error,'updated Participant=' + p);
try {
res.statusCode = 200;
update p;
sf_jsonResponse = '{"response": {"status": "Sucess", "message": "Participant record:'+uNum +' ' +'is updated in Salesforce"}}';
res.responseBody = blob.valueOf(sf_jsonResponse);
return;
} catch ( Exception ex ) {
res.statusCode = 500;
sf_jsonResponse = '{"response": {"status": "Failure", "message": "Participant record:'+uNum +' '+ ex + '"}}';
res.responseBody = blob.valueOf(sf_jsonResponse);
return;
}
}
global class Wrapclass {
public String status;
public String responseBody;
}
}
Here is my Test class..
@isTest(seeAllData=false)
Public class Test_RESTParticipantHandler {
public static testMethod void testdoPost() {
System.RestContext.request = new RestRequest();
System.RestContext.response = new RestResponse();
Account a = new Account(Name = 'Test', RK_ID__c='106',PR_FE_Branded__c= true);
insert a;
String orgId=a.id;
Contact c = new Contact();
c.firstname = 'Wain';
c.lastname = 'R';
c.AccountId = orgId;
c.email = 'Wain@test.com';
c.phone = '6884382997';
c.mailingstreet = '123 Test Ave';
c.mailingcity = 'Somewhere';
c.mailingstate = 'MA';
c.mailingPostalCode = '87945';
c.mailingcountry = 'US';
c.User_Num__c='1234567';
insert(c);
RestRequest req = new RestRequest();
RestResponse res = new RestResponse();
REST_ParticipantHandler.Wrapclass reqst=new REST_ParticipantHandler.Wrapclass();
reqst.status= 'Success';
reqst.responseBody ='{"state":"CA","riskTolerance":"Typical for your age","retirementAge":"70",alPortfolio":"65627.50","phoneContactPreference":"SEC Required Only","email":"","homePhone":"5555555555","title":"","mailingAddress":"13630 SE 231ST ST","userNum":"13328911","lastInitial":"R","city":"Sunnyvale","zip":"94086","foreignResident":"0","workPhone":"4084986934","otherPhone":"5555555555",","isFeBrand":"1","primaryAccountPlan":"Voluntary Investment Plan (VIP)","convertedFromUserNum":"","convertedToUserNum":"","countryCode":"US"}';
String JsonMsg=JSON.serialize(reqst);
req.requestURI ='/services/apexrest/UpdateParticipant';
req.httpMethod = 'POST';
req.requestBody = Blob.valueof(JsonMsg);
RestContext.response= res;
RestContext.request = req;
REST_ParticipantHandler.UpdateParticipant();
//System.assertEquals('true', results.success);
//System.assertEquals(10, results.records.size());
}
}
*****************************************************************
Im getting an error "System.QueryException: unexpected token: 'FROM'"
**********************************************************************
Amit Chaudhary 8
Please try to add space before and after from keywork and try again
KrForce
Thanks for your response Amit...issue was with extra comma after Email in "string qFields=String.join(FieldMap.values(), ', ');" so removed extra comma by doing "qFields.removeEnd(',');". Query issue is resolved but still the coverage is 40% its skiping Line 31 ,38 and 58 evein we set UserNum and Status code. any suggestions?