+ Start a Discussion
Nihon TaisaiNihon Taisai 

Correct HttpPatch and correct test for it

I need to update a right record with ExternalID = Id of inserted record. And I try to check this field (ExternalID) in SOQL, but get an error System.QueryException: List has no rows for assignment to SObject. What is wrong here?
@HttpPatch
global static void upd() {
    RestRequest req = RestContext.request;
    String thisID = req.params.get('Id');
    Product__c product = [SELECT Id FROM Product__c WHERE ExternalID__c =: thisID];
    Map<String, Object> params = (Map<String, Object>)JSON.deserializeUntyped(req.requestbody.tostring());
    for(String fieldName : params.keySet()) {
        product.put(fieldName, params.get(fieldName));
    }
    update product;
}
Test (coverage 100%, but error):
@isTest
static void testupd() {
    Product__c test = new Product__c(Name__c = 'Orange');
    insert test;
    RestRequest req = new RestRequest();
    req.requestUri = System.URL.getSalesforceBaseUrl().toExternalForm() +
                     '/services/apexrest/Product__c/ExternalID__c/'
                     + test.Id;
    //even this can't help to put id of inserted test-product into ExternalID__c:
    req.params.put('ExternalID__c', test.Id);
    req.httpMethod = 'PATCH';
    req.addHeader('Content-Type', 'application/json');
    req.requestBody = Blob.valueOf('{"Name__c": "Cherry"}'); 
    RestContext.request = req;
    //update method:
    TheClass.upd();
    //Error is here:
    Product__c updatedRecord = [SELECT Name__c
                                FROM Product__c
                                WHERE ExternalID__c =: test.Id];
    System.assert(updatedRecord.Name__c == 'Cherry');
}

 
Raj VakatiRaj Vakati
What is the value in ExternalID__c  and req.params.get('Id') ?? 

Is its salesforce record id or extenal System id ? and is its present in the system ??


try this code
 
@HttpPatch
global static void upd() {
    RestRequest req = RestContext.request;
    String thisID = req.params.get('Id');
	Product__c product = new Product__c ();
    product = [SELECT Id FROM Product__c WHERE ExternalID__c =: thisID];
    Map<String, Object> params = (Map<String, Object>)JSON.deserializeUntyped(req.requestbody.tostring());
    for(String fieldName : params.keySet()) {
        product.put(fieldName, params.get(fieldName));
    }
    upsert product thisID ;
}

 
Nihon TaisaiNihon Taisai
Thank you, Raj Vakati. But I need to update correct (by ExternalID__c) record if it changes. And anyway "upsert product ExternalID__c;" returns an error:
System.DmlException: Upsert failed. First exception on row 0 with id a001000001btXLrAAM; first error: MISSING_ARGUMENT, ExternalID__c not specified: []