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
PJayaPJaya 

List has no rows for assignment to SObject

here is my Apex class

 

 

global class Lead_Conversion {

   WebService static String convertLead(Id leadId){
       system.debug('++++++++++LEAD ID***********'+leadId);
       Account  acc;
       String status;
       String errorIndication='';
       try{
           Lead lead1=[SELECT OwnerId,Account_Owner_SFDC_Id__c,Opportunity__c,Sfdc_Account_BackendId__c,Company,Email,Circle__c,City,Account__c,Product_Type__c,SME_TTL_Product__c,Product_Quantity__c,Proposed_Order_value_In_Rs_Lakh__c From Lead where Id=:leadId];
        
        
           /*Lead lead1=[Select Account__c,Account_Owner_SFDC_Id__c,Opportunity__c,Website,TotalNumberofDisconnections__c,TotalLeadsReassigned__c,TotalLeadsGenerated__c,TotalLeadsAssigned__c,Title,
                       SystemModstamp,Street,Status,State,Sfdc_Account_BackendId__c,Salutation,SME_TTL_Product__c,SME_SemiAdminIDMID__c,SLALeads__c,
                        SFDC_Lead_ID__c,Retail_Lead_Value__c,Remarks__c,RecordTypeId,Rating,Proposed_Order_value_In_Rs_Lakh__c,Product__c,Product_Type__c,
                        Product_Quantity__c,PostalCode,Phone,OwnerId,OpenCases__c,NumberOfEmployees,No_of_Del_Active__c,Name,Mode_of_Entry__c,MasterRecordId,
                        LeadsGenerated__c,LeadsActedOn__c,Lead_Type__c,Lead_Region__c,Lead_Priority__c,Lead_Closure_Reason__c,Lead_Classification__c,
                        Lead_Captured_By_IDM_ID__c,LeadSource,LeadRecType__c,LeadClosedDate__c,LastName,LastModifiedDate,LastModifiedById,LastActivityDate,
                        LPMS_Lead_ID__c,LPMS_ID_from_ePOS__c,LPMS_ID_Discrepancy__c,IsUnreadByOwner,IsDeleted,IsConverted,Industry,Id,Generated_Date_and_Time__c,
                        Follow_Up_date_time__c,FirstName,EmailBouncedReason,EmailBouncedDate,Email,Description,Del_No__c,Del_Activation_Status__c,Del_Activation_State__c,
                        DateLeadActedOn__c,CustomerName__c,CreatedDate,CreatedById,Country,ConvertedOpportunityId,ConvertedDate,ConvertedContactId,
                        ConvertedAccountId,Conversion_Field_Update__c,Company_segment__c,Company_Type__c,Company,City,Circle__c,Area_Name__c,AnnualRevenue,
                        Account_Trigger__c,Account_Number__c From Lead where Id=:leadId];*/
                        
          system.debug('=========lead1.OwnerId========'+lead1.OwnerId+'++++++++++Account Owner ID***********'+lead1.Account_Owner_SFDC_Id__c+'+++++++++++++++lead1.Opportunity__c++++++++++++++'+lead1.Opportunity__c+'++++lead1.Sfdc_Account_BackendId__c++++++++'+lead1.Sfdc_Account_BackendId__c); 
           map<Id,SME_Product__c> smettlproductmap=new Map<Id,SME_Product__c>([select ID,Name,List_Price__c,Product_Family__c,Product_Group__c from SME_Product__c]);
             system.debug('smettlproductmap=====>>>>'+smettlproductmap);
                 
           Schema.RecordTypeInfo TtlOppRecordtype= Schema.SObjectType.Opportunity.getRecordTypeInfosByName().get('SME New/Upgrade TTL Product Opportunity');
           Id TtlOpprecordtypeId=TtlOppRecordtype.getRecordTypeId();
            system.debug('=====TtlOpprecordtypeId========='+TtlOpprecordtypeId);
           Schema.RecordTypeInfo TclOppRecordtype= Schema.SObjectType.Opportunity.getRecordTypeInfosByName().get('SME New/Upgrade TCL Product Opportunity');
           Id TclOpprecordtypeId=TclOppRecordtype.getRecordTypeId();
               system.debug('============='+TclOpprecordtypeId);
               system.debug('==LeadConversion=====Sfdc_Account_BackendId__c=============='+lead1.Sfdc_Account_BackendId__c);
           boolean accExist=true;
           boolean accInserted=false;
           if(lead1.Sfdc_Account_BackendId__c==null){
           try{
            Schema.RecordTypeInfo SmeAccountrecordtype= Schema.SObjectType.Account.getRecordTypeInfosByName().get('SME Account');
            Id AccountRecTypeId=SmeAccountrecordtype.getRecordTypeId();          
            system.debug('========AccountRecTypeId========='+AccountRecTypeId);

                User usrs=[select Name,IDM_Id__c,IDM_ID_of_USer__c from User where Id=:lead1.OwnerId];
                Integer AccchkExists=[select count() from Account where Name=:lead1.Company];
                
                if(AccchkExists>0){                
                    system.debug('Account already exists with the name: '+lead1.Company+' so new account cannot be created with same name');
                }else{
                    acc = new Account();               
                        acc.Name = lead1.Company;
                        acc.Type_Of_Corporate__c = 'SME A';
                        acc.OwnerId =lead1.OwnerId;
                        acc.OwnerEmail__c =lead1.Email;
                        acc.RecordtypeId = AccountRecTypeId;
                        acc.Vertical_Segment__c='SME';
                        acc.TTL_Status__c='Non-Verified';
                        acc.TCL_Status__c='Non-Verified';
                        acc.Share_to_SalesCoordinator__c='YES';
                        acc.Circle__c=lead1.Circle__c;
                        acc.City__c=lead1.City;
                        acc.OwnerIDMId__c=usrs.IDM_Id__c;
                    Insert acc; 
                    accInserted=true;
                }               
            }catch(Exception e){
                status='Failure';
                accExist=false;              
                errorIndication=' Failed while creating account ';
                system.debug(e);            
            }
           }           
           boolean currentLeadUpdated=true;              
           if(accInserted){
             try{
                system.debug('====accName===='+acc.Name+'=====accID====='+acc.Id);
                lead1.Sfdc_Account_BackendId__c=acc.Id;
                lead1.Account__c=acc.Id;
                update lead1;
                currentLeadUpdated=true;
            }catch(Exception e){
                currentLeadUpdated=false;
                system.debug('Exception while updatating lead');
                system.debug(e);
            } 
           }
           if(currentLeadUpdated){
               system.debug('======into loop currentLeadUpdated--==========');
                lead1=null;
                lead1=[SELECT OwnerId,Account_Owner_SFDC_Id__c,Opportunity__c,Sfdc_Account_BackendId__c,Company,Email,Circle__c,City,Account__c,Product_Type__c,SME_TTL_Product__c,Product_Quantity__c,Proposed_Order_value_In_Rs_Lakh__c From Lead where Id=:leadId];

              (here the base on the id query is fetched but while executing the query its raising this error plz help me out)
               /* lead1=[Select Account__c,Account_Owner_SFDC_Id__c,Opportunity__c,Website,TotalNumberofDisconnections__c,TotalLeadsReassigned__c,TotalLeadsGenerated__c,TotalLeadsAssigned__c,Title,
                        SystemModstamp,Street,Status,State,Sfdc_Account_BackendId__c,Salutation,SME_TTL_Product__c,SME_SemiAdminIDMID__c,SLALeads__c,
                        SFDC_Lead_ID__c,Retail_Lead_Value__c,Remarks__c,RecordTypeId,Rating,Proposed_Order_value_In_Rs_Lakh__c,Product__c,Product_Type__c,
                        Product_Quantity__c,PostalCode,Phone,OwnerId,OpenCases__c,NumberOfEmployees,No_of_Del_Active__c,Name,Mode_of_Entry__c,MasterRecordId,
                        LeadsGenerated__c,LeadsActedOn__c,Lead_Type__c,Lead_Region__c,Lead_Priority__c,Lead_Closure_Reason__c,Lead_Classification__c,
                        Lead_Captured_By_IDM_ID__c,LeadSource,LeadRecType__c,LeadClosedDate__c,LastName,LastModifiedDate,LastModifiedById,LastActivityDate,
                        LPMS_Lead_ID__c,LPMS_ID_from_ePOS__c,LPMS_ID_Discrepancy__c,IsUnreadByOwner,IsDeleted,IsConverted,Industry,Id,Generated_Date_and_Time__c,
                        Follow_Up_date_time__c,FirstName,EmailBouncedReason,EmailBouncedDate,Email,Description,Del_No__c,Del_Activation_Status__c,Del_Activation_State__c,
                        DateLeadActedOn__c,CustomerName__c,CreatedDate,CreatedById,Country,ConvertedOpportunityId,ConvertedDate,ConvertedContactId,
                        ConvertedAccountId,Conversion_Field_Update__c,Company_segment__c,Company_Type__c,Company,City,Circle__c,Area_Name__c,AnnualRevenue,
                        Account_Trigger__c,Account_Number__c From Lead where Id=:leadId]; */
           }
           system.debug('==lead again querying========lead1.Account_Owner_SFDC_Id__c;==========='+lead1.Account_Owner_SFDC_Id__c);
           system.debug('====lead1.Opportunity__c===='+lead1.Opportunity__c+'====accExist==='+accExist);
           If(lead1.Opportunity__c==null && accExist){
            system.debug('=========If==lead1.Opportunity__c==null  accExist=================');
            boolean toinsertOpp=true;
               Opportunity opp1=new Opportunity();
               Products_Services__c tclpro = new Products_Services__c();
               opp1.Name='ConvertedLead';
                //opp1.AccountId=lead1.Account__c;
               if(lead1.Sfdc_Account_BackendId__c==null && accExist){
                  system.debug('====AccountExistd===lead1.Account__c=========='+lead1.Account__c);
                  opp1.AccountId=lead1.Account__c;                
               }else if(lead1.Sfdc_Account_BackendId__c==null && !accExist){
                  system.debug('==AccountNotExists===acc.Id====='+acc.Id);
                  opp1.AccountId=acc.Id;
               }else{
                  system.debug('==Account===lead1.Account__c====='+lead1.Account__c);
                  opp1.AccountId=lead1.Account__c;
               }
               //opp1.OwnerId=lead1.Account_Owner_SFDC_Id__c;
               //opp1.OwnerId=acc.OwnerId;
               opp1.OwnerId=lead1.OwnerId;
               opp1.Type='New';
               Date dt1=Date.today();
               opp1.CloseDate=dt1;
               opp1.Opportunity_source__c='LEAD CONVERT';
               opp1.StageName='Identified Opportunity';
               system.debug('====lead1.Product_Type__c======'+lead1.Product_Type__c);
               if(lead1.Product_Type__c=='TTL'){
                system.debug('================lead1.Product_Type__c==TTL==============');
                   opp1.RecordTypeId=TtlOpprecordtypeId;
                   system.debug('============smettlproductmap.get(lead1.SME_TTL_Product__c).List_Price__c======================');
                   Integer smetlmapVal=null;
                   try{
                    smetlmapVal=Integer.valueOf(smettlproductmap.get(lead1.SME_TTL_Product__c).List_Price__c);
                   }catch(Exception e){
                    status='Failure';
                    errorIndication='Unable to find the product id for this lead';
                    system.debug(e);
                   }
                   system.debug('================smetlmapVal================='+smetlmapVal);                   
                   if(smetlmapVal!=null){
                         if(smetlmapVal > 0){
                           opp1.SME_Product__c=lead1.SME_TTL_Product__c;
                           opp1.TotalOpportunityQuantity=lead1.Product_Quantity__c;
                          }else if(smetlmapVal==null ||smetlmapVal==0){
                           opp1.SME_Product__c=lead1.SME_TTL_Product__c;
                           opp1.TotalOpportunityQuantity=lead1.Product_Quantity__c;
                           opp1.Annual_Recurring_Charges__c=lead1.Proposed_Order_value_In_Rs_Lakh__c;
                           opp1.Manage_Service_Rentals__c=0;
                           opp1.One_Time_Charges__c=0;
                        }
                   } 
                }else if(lead1.Product_Type__c=='TCL'){
                   system.debug('================lead1.Product_Type__c==TL==============');
                   opp1.RecordTypeId=TclOpprecordtypeId;
                   opp1.ForecastCategoryName='Pipeline';
                   opp1.Is_Standard_NonStandard__c='Standard';
               }else{
                 system.debug('================lead1.Product_Type__c==false==============');
                 toinsertOpp=false;
                 status='Failure';
                 errorIndication='Product selected is not correct';
                 system.debug('0000000   status======'+status+' errorIndication========'+errorIndication);                 
               }
               system.debug('111111  status======'+status+' errorIndication========'+errorIndication);
               system.debug('================toinsertOpp=============='+toinsertOpp);
                   if(toinsertOpp){
                       try{                    
                           insert opp1;
                           status='Success'; 
                           errorIndication='success';
                           lead1.Opportunity__c=opp1.Id;
                           update lead1;                       
                       }catch(Exception e){
                            status='Failure';
                            if(errorIndication.length()==0)errorIndication='Opportunity not created due to data mismatch';
                            system.debug('2222222   status======'+status+' errorIndication========'+errorIndication);
                            system.debug('Exception while trying to insertion/updataion of the oppurtunity');
                            system.debug(e);                
                       } 
                   }else{
                      status='Failure';
                      errorIndication='opportunity exists for this lead';
                      system.debug('333333   status======'+status+' errorIndication========'+errorIndication);
                   }
           }
       }catch(Exception e){
            status='Failure';
            errorIndication=' ServerError';
            system.debug('Exception=========Occured=====');
            system.debug('=======ExcepDetails=============='+e.getMessage());
        }
        status=status+'**'+errorIndication;
        system.debug('===status===================='+status);
        system.debug('==errorIndication============='+errorIndication);
        return status;
    }
    
    
}

 

 

 

My Test Class is

===============

 

@isTest (SeeAllData = true)  
global class LeadConversionTestCase{ 
          Static testmethod void testManage_bulklead() {
          
        //Get Show Manager profile Id.
        Profile p1 = [SELECT Id FROM Profile WHERE Name ='SME Semi_Admin'];
        system.debug('============Profile======p1=========='+p1);
        Profile p2 = [SELECT Id FROM Profile WHERE Name ='SME_Supervisor'];
        system.debug('============Profile======p2=========='+p2);
        User semiAdmin = new User(Alias = 'uc1233', Email='uc123@sfdc.com', EmailEncodingKey='UTF-8', LastName='Testing User2', 
                                    LanguageLocaleKey='en_US', LocaleSidKey='en_US', ProfileId = p1.Id, 
                                    TimeZoneSidKey='America/Los_Angeles', UserName='nU123@test.com');
           insert semiAdmin;
           User brm1 = new User(Alias = 'uc1233', Email='uc1234@sfdc.com', EmailEncodingKey='UTF-8',FirstName ='TTL', LastName='TestingUser', 
                                    LanguageLocaleKey='en_US', LocaleSidKey='en_US', ProfileId = p2.Id,
                                    TimeZoneSidKey='America/Los_Angeles', UserName='nU1234@test.com',SME_User_Region__c='AP',SME_RoleName__c='SALESHEAD');  
            insert brm1;
            Schema.RecordTypeInfo SmeLeadrecordtype= Schema.SObjectType.Lead.getRecordTypeInfosByName().get('Company Lead');
            system.debug('==========SmeLeadrecordtype================================='+SmeLeadrecordtype);
            
            Id SmeLeadrecordtypeId=SmeLeadrecordtype.getRecordTypeId();
          try{
             Test.StartTest();
          
            //Run test as user whose profile is show Manager                        
            System.runas(semiAdmin) {
            
              
            RecordType rc = [SELECT Id FROM RecordType WHERE Name='SME TTL Products'];
            system.debug('==================rc============='+rc);
            
            SME_Product__c prdSME= new SME_Product__c();
                prdSME.Name='TESTPRO';
                prdSME.Product_Group__c='CDMA Mobile';
                prdSME.RecordTypeID=rc.id;
                prdSME.Product_Manager__c=semiAdmin.id;//SME Product
                prdSME.Product_Family__c='Fixed Voice';
                prdSME.List_Price__c=500;
                prdSME.Active__c=TRUE;
            insert prdSME;     
                prdSME.Lock__c='NO';
            update prdSME;
            system.debug('=============jjjjj====semiAdmin.Id=============='+semiAdmin.Id);
            Lead testleadobj=new Lead(LastName='jakc',Company='jakc',Status='Qualified',Company_segment__c='SME A',Lead_Type__c='Company',Lead_Region__c='AP',Product_Type__c='TTL',Product__c=prdSME.Id,SME_TTL_Product__c=prdSME.Id,OwnerId=semiAdmin.Id,RecordTypeId=SmeLeadrecordtype.getRecordTypeId());
            insert testleadobj;
            system.debug('=============jjjj====testleadobj.OwnerId============='+testleadobj.OwnerId+'====testleadobj.Id=='+testleadobj.Id);
           // testleadobj.Status='Closed-Sold';
            //update testleadobj;
           // system.debug('===============testleadobj============'+testleadobj);
           // Lead fetId=[select Name,Id from Lead where Id=:testleadobj.Id];
           // system.debug('=========fetId========'+fetId.Id);
            Lead_Conversion.convertLead(testleadobj.Id);    (here the id is passed to the apex class)

 

 

 

 

 

 

 

 

 

 

Best Answer chosen by Admin (Salesforce Developers) 
PJayaPJaya

Dear cherrlin,

 

I have got the solution

 

i have done the mistake where i have no access to that object now i have run assystem admin which i have achived

 

but error which returnrd is incorrect...

 

Thanks a lot..Have a nice day..

 

Jaya.

All Answers

SharathChandraSharathChandra

In this situation i'll first check all the queries are return values with an hardcoded id first.

If its running without any error then i'll check with leadid.

In this you commented some code send me the exact code. i'll try it.

 

PJayaPJaya

hi

 
i dont have any problem with my class when i am calling from click on event or trigger
 
only iam facing with test class my doubt is it possible to send the RecordId to the apex calss in testClass
 
 
can u help me ...
 
Thanks
Jaya.
SharathChandraSharathChandra

Yes it is possible to send id form test class also.

You can also check that id value when you run the test class.

download the log and check it.

PJayaPJaya

Dear cherrlin,

 

Id is getting passed but the issue is when i trying to query with that id iam unable to fetch the record there iam getting this exception

 

System.QueryException: List has no rows for assignment to SObject

 

but befor trying to retrive i printing the ID its getting displayed

 

1)Lead testleadobj=newLead(LastName='jakc',Company='jakc',Status='Qualified',Company_segment__c='SME A',Lead_Type__c='Company',Lead_Region__c='AP',Product_Type__c='TTL',Product__c=prdSME.Id,SME_TTL_Product__c=prdSME.Id,OwnerId=semiAdmin.Id,RecordTypeId=SmeLeadrecordtype.getRecordTypeId());

 

2)insert testleadobj;

3)system.debug('=====testleadobj.Id===='+testleadobj.Id);

 

4)Lead  leds =[select LastName,Company,Status fromLeadwhere Id=:testleadobj.id];

 

in the above code till 3rd line its executing after executing 4 line iam geting the exception

System.QueryException: List has no rows for assignment to SObject

 

 

plz help me out

 

 

Thanks,

Jaya

 

SharathChandraSharathChandra

Yes you wont be getting it because all the operations which you done in test class are temporary. It wont be commited in the production or sandbox

 

and also there is also no data present in the org with respect to that id which you got after inserting the record.

 

Solution is use annotation @isTest(SeeAllData == true) which you have also done it

and use the lead id which is already present in Production or Sandbox.

 

PJayaPJaya

My case based on the inserted record Id i need to run the apex calss so how can i achive the Code coverage for the apex class

 

Thanks,

jaya

SharathChandraSharathChandra

Just do one thing in the test class

do this

Lead_Conversion.convertLead(testleadobj.Id);

in place of testleadobj.id you provide the hardcoded id which is already present your sandbox or production.

and run the test class

PJayaPJaya

Even with the hardcoded iam unable to achive this.

 

 

Thanks,

Jaya

SharathChandraSharathChandra

Lead_Conversion.convertLead('your id');


Same thing you have done ???

right??

any errors?????

 

PJayaPJaya

Yeah Same i have done and same error iam getting List has no rows for assignment to SObject

 

Thanks,

Jaya

 

 

PJayaPJaya

Even i have tried  by retriving the existing data on leads and sending the lead id to the Lead_conversion class

 

but retriving the  existing leads itself its giving zero records as test case  doesnt pick the Saleforce database records i think so

 

Thanks,

JAya

SharathChandraSharathChandra

Does the id which you gave has any respective lead record in production?

PJayaPJaya

Yeah iam having the record..

 

Thanks,

Jaya

PJayaPJaya

even when i trying to get exists data iam geting zero records here is log

 

12:55:21.386 (3386733000)|SOQL_EXECUTE_BEGIN|[46]|Aggregations:0|select Id, Company, LastName from Lead
12:55:21.491 (3491856000)|SOQL_EXECUTE_END|[46]|Rows:0
12:55:21.492 (3492214000)|USER_DEBUG|[48]|DEBUG|=======lldSize======0

 

 

Thanks

Jaya

SharathChandraSharathChandra

When you mention @isTest(SeeAllData == true)

You can access you database records in test class.

PJayaPJaya

Dear cherrlin,

 

I have got the solution

 

i have done the mistake where i have no access to that object now i have run assystem admin which i have achived

 

but error which returnrd is incorrect...

 

Thanks a lot..Have a nice day..

 

Jaya.

This was selected as the best answer
SharathChandraSharathChandra
Did you mention the @isTest(SeeAllData== true) "Legal Disclaimer: This electronic message and all contents contain information from Cybage Software Private Limited which may be privileged, confidential, or otherwise protected from disclosure. The information is intended to be for the addressee(s) only. If you are not an addressee, any disclosure, copy, distribution, or use of the contents of this message is strictly prohibited. If you have received this electronic message in error please notify the sender by reply e-mail to and destroy the original message and all copies. Cybage has taken every reasonable precaution to minimize the risk of malicious content in the mail, but is not liable for any damage you may sustain as a result of any malicious content in this e-mail. You should carry out your own malicious content checks before opening the e-mail or attachment." www.cybage.com