function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Abhishek Pal 33Abhishek Pal 33 

How to test object id in salesforce.

Hello Everyone,

How do I get object id inserted through test cases in salesforce.

//Method which i need to test 

 public static Product__c addProduct(Product__c product){
          Product__c productToPersist = product;
        Product__c  insertedProduct;
                insert productToPersist;
                insertedProduct=[select Id, Short_Material_Number__c from Product__c where UPC_Code_for_Consumer_Units__c = :productToPersist.Short_Material_Number__c];  // When I am calling this method I am getting System.QueryException: List has no rows for assignment to SObject in test method.

//This is my testcase for above method

@isTest static void save()
Product__c insertedProduct;
// here I am inserting addProduct through json.

Note: As per my understanding the data is not persisted in test case then how do I get the object id from the object when I am trying to insert in salesforce. As we can see that the reason why I am getting this exception because it is returning 0 rows and unable to persist the data and cdnt get the object id also.

Before inserting check if productToPersist.Short_Material_Number__c has a value. You can do that in two ways.
  1. Use a System.debug and check the log if there is a value.
  2. You can also do an inster if only productToPersist.Short_Material_Number__c have a value. Use if stamtement in the try block before the insert DML.
My 2 cnets - It seems that you two fields for same value. UPC_Code_for_Consumer_Units__c and Short_Material_Number__c. If they are not the same value, and only carries partial similarities then use methods likes contains(substring).