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
Pintu BudakotiPintu Budakoti 

Getting error while testing controller :- System.QueryException: List has no rows for assignment to SObject

Hi everyone,I am new to salesforce and I'm having trouble with a test class. I'm passing a value to the target class variable but when the SOQL query executes, it returns "System.QueryException: List has no rows for assignment to SObject". Please help


Apex Class

global class MembershipContractPreview_ctrl { 
    public String save { get; set; } 
    public String imgSource{get;set;}
    public String selectedSobject {get;set;}
    public Account objAccount {get;set;}
    public Account acc{get;set;}
    public list<MappingWrapper> listMappingWrapper{get;set;}
    public list<string> objects {get;set;}
    public string editSelectedObject {get;set;}
    public list<SelectOption> selectedObjfields {get;set;}
    public string selectedObj {get;set;}
    public Integer index {get;set;}
    public string membershipType{ get;set; }
    public string frequency{ get;set; }
    public string quantities{ get;set; }
    public string members{ get;set; }  
    public string contractDownloadLink{get;set;}
    
    public MembershipContractPreview_ctrl () { 
        //isContractSigned = false;
        frequency = apexpages.currentpage().getparameters().get('token');
        system.debug('>>>>>>>>>>>>>>>>>>>>'+apexpages.currentpage().getparameters().get('token'));
        selectedObjfields = new list<SelectOption>();
        selectedSobject = 'Account';
        init();
    }
    
    
    public void onUpdate(){
        Account acc = new Account(Id = objAccount.Id);
        if(null != imgSource){
            acc.Signature__c='<img src="'+imgSource+'" width="230px" height="71px"></img>';
            acc.Signature_Date__c = system.Now();
            objAccount.Signature__c ='<img src="'+imgSource+'" width="230px" height="71px"></img>';
            objAccount.Signature_Date__c = system.Now();
            //isContractSigned = true;
        }
        //acc.Patient_Type__c = 'Member';
        //acc.Membership_Level__c = 'Child';
        //acc.Membership_Type__c = membershipType;
        //acc.Quantity__c= '1';
        update acc;
        //sendAndUploadContract();//acc.Id);
    }
    
    public void sendAndUploadContract(){
        PageReference pdf = Page.Membershipformpdf;
        // add parent id to the parameters for standardcontroller
        pdf.getParameters().put('id',objAccount.Id);        
        // create the new attachment
        Attachment attach = new Attachment();    
        // the contents of the attachment from the pdf
        Blob body;        
        try {            
            // returns the output of the page as a PDF
            body = pdf.getContent();            
        // need to pass unit test -- current bug    
        } catch (VisualforceException e) {
            body = Blob.valueOf('Is you do not recieve correctly Formated contract, Please contact to Receptionist!');
        }
        ContentVersion conVer = new ContentVersion();
        conVer.ContentLocation = 'S'; // S specify this document is in SF, use E for external files
        conVer.PathOnClient = 'MHC Membership contract_Oct 2018.pdf'; // The files name, extension is very important here which will help the file in preview.
        conVer.Title = 'MHC Membership contract_Oct 2018.pdf'; // Display name of the files
        conVer.VersionData = body;//EncodingUtil.base64Decode(body); // converting your binary string to Blog
        insert conVer;
        Id conDoc = [SELECT ContentDocumentId FROM ContentVersion WHERE Id =:conVer.Id].ContentDocumentId;
        contractDownloadLink = 'https://dev-myhealthcaretestenv.cs89.force.com/sfc/servlet.shepherd/version/download/'+conVer.Id+'?asPdf=false&operationContext=CHATTER';     
        //Create ContentDocumentLink
        ContentDocumentLink cDe = new ContentDocumentLink();
        cDe.ContentDocumentId = conDoc;
        cDe.LinkedEntityId = objAccount.Id; // you can use objectId,GroupId etc
        cDe.ShareType = 'I'; // Inferred permission, checkout description of ContentDocumentLink object for more details
        cDe.Visibility = 'AllUsers';//'InternalUsers';
        insert cDe;
        list<Messaging.SingleEmailMessage> messagingList = new List<Messaging.SingleEmailMessage>();
        Messaging.SingleEmailMessage mail =  new Messaging.SingleEmailMessage();  
        list<String> toAddresses = new list <string>{'usman.sfdc@gmail.com','pintub.sfdc@gmail.com'};
        list<String> ccAddresses = System.Label.GoCardless_CC_Email_Address.split(',');
        mail.setCcAddresses(ccAddresses);
        mail.setToAddresses(toAddresses); 
        mail.setSubject(String.Format(System.Label.GoCardless_Email_Subject, new list<String>{'Test 123'}));
        mail.setHtmlBody(String.Format(System.Label.GoCardless_Email_Body, new list<String>{'Test 123'}));
        List<Messaging.Emailfileattachment> fileAttachments = new List<Messaging.Emailfileattachment>();        
        // Add to attachment file list
        Messaging.Emailfileattachment efa = new Messaging.Emailfileattachment();
        efa.setFileName('MHC Membership contract_Oct 2018.pdf');
        efa.setBody(conVer.VersionData);
        fileAttachments.add(efa);
        mail.setFileAttachments(fileAttachments);
        messagingList.add(mail);
        if(!messagingList.isEmpty()){
            Messaging.sendEmail(messagingList);
        }
    }
         
    public void init(){
        string objSobject = '';
        objects = new list<string>();
        objAccount = [select Name,Patient_Type__c ,Quantity__c,Billing_Address__c,List_Of_Members_Covered_By_The_Contract__c,Membership_Start_Date__c ,ContactId__c,
                      Membership_Change_Dates__c,Signature__c,Signature_Date__c,Contract_Sent_Date__c,Total_Monthly_Membership_Fee__c,Home_Clinic__c ,Membership_Type__c ,
                      Membership_Level__c ,Payment_Frequency__c, (Select Id, ContentDocumentId From ContentDocumentLinks order by ContentDocument.CreatedDate DESC limit 1)  from Account where id=:apexpages.currentpage().getparameters().get('token')];
        listMappingWrapper = new list<MappingWrapper>{new MappingWrapper()};
        if(objAccount != null && objAccount.ContentDocumentLinks.size() > 0){
            contractDownloadLink = 'https://dev-myhealthcaretestenv.cs89.force.com/sfc/servlet.shepherd/version/download/'+[SELECT Id FROM ContentVersion WHERE ContentDocumentId=:objAccount.ContentDocumentLinks.get(0).ContentDocumentId limit 1].Id+'?asPdf=false&operationContext=CHATTER';    
        }        
        if(Apexpages.currentPage().getParameters().get('editSelectedObject') == null){ 
            objSobject = selectedSobject ;  
        }else{
            objSobject = Apexpages.currentPage().getParameters().get('editSelectedObject'); 
        } 
    }
    public class MappingWrapper{
        public string member{get;set;}
        public string quantity{get;set;}
        public MappingWrapper(){}
        public MappingWrapper(string member,string quantity){
            this.member = member;
            this.quantity = quantity;
        }
    }
    public void addMember(){
        listMappingWrapper.add(new MappingWrapper());
    }
    public void removeMember(){
        listMappingWrapper.remove(index);
    }
    public List<SelectOption> getMembersPicklist(){
        List<SelectOption> options = new List<SelectOption>();            
        Schema.DescribeFieldResult fieldResult =
        Account.Membership_Level__c.getDescribe();
        List<Schema.PicklistEntry> ple = fieldResult.getPicklistValues();            
        for( Schema.PicklistEntry f : ple){
          options.add(new SelectOption(f.getLabel(), f.getValue()));
        }       
        return options;
    }
    
    public List<SelectOption> getQuantitiesPicklist(){
        List<SelectOption> options = new List<SelectOption>();            
        Schema.DescribeFieldResult fieldResult =
        Account.Quantity__c.getDescribe();
        List<Schema.PicklistEntry> ple = fieldResult.getPicklistValues();            
        for( Schema.PicklistEntry f : ple){
          options.add(new SelectOption(f.getLabel(), f.getValue()));
        }       
        return options;
    } 
    
    public List<SelectOption> getFrequencyPicklist(){
        List<SelectOption> options = new List<SelectOption>();            
        Schema.DescribeFieldResult fieldResult =
        Account.Payment_Frequency__c.getDescribe();
        List<Schema.PicklistEntry> ple = fieldResult.getPicklistValues();            
        for( Schema.PicklistEntry f : ple){
          options.add(new SelectOption(f.getLabel(), f.getValue()));
        }       
        return options;
    }
    
    public List<SelectOption> getMembershipTypePicklist(){
        List<SelectOption> options = new List<SelectOption>();            
        Schema.DescribeFieldResult fieldResult =
        Account.Membership_Type__c.getDescribe();
        List<Schema.PicklistEntry> ple = fieldResult.getPicklistValues();            
        for( Schema.PicklistEntry f : ple){
          options.add(new SelectOption(f.getLabel(), f.getValue()));
        }       
        return options;
    }
    public void sendEmail(){}
    public pageReference onSend(){ 
        pageReference pr = new pageReference('/'+objAccount.Id);
        pr.setRedirect(true);    
        Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
        mail.setTargetObjectId(objAccount.ContactId__c);
        mail.setTemplateId('00X0E000000rjg7'); 
        mail.setWhatId(objAccount.Id);    
        mail.setBccSender(false);
        mail.setReplyTo('Laxminarayan.sfdc@gmail.com');
        mail.setToAddresses(new List<String>{'usman.sfdc@gmail.com'});
        mail.setSenderDisplayName('Membership Contract from MyHealthCare Clinic');
        mail.setSaveAsActivity(false); 
        Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail }); 
        Account ac2Update = new Account(id=objAccount.Id);
        ac2Update.Contract_Sent_Date__c = System.Now();
        ac2Update.Member_Status__c = 'Pending'; 
        Update ac2Update;
        return pr;
    }         
}


Test class 

@isTest
private class MembershipContractPreview_ctrl_Test{
     static testMethod void membercontract(){
   Test.startTest();
  MembershipContractPreview_ctrl memC = new MembershipContractPreview_ctrl();
   MembershipContractPreview_ctrl.MappingWrapper mw = new MembershipContractPreview_ctrl.MappingWrapper();
       mw.member = 'member';
        mw.quantity = 'quantity';
        Account objacc = new Account();
         objacc.Patient_Type__c = 'Member';
         //objacc.Name = 'Member'; 
         objacc.List_Of_Members_Covered_By_The_Contract__c = 'Member';
         objacc.Membership_Start_Date__c  = system.Today();
         objacc.Membership_Change_Dates__c = system.Today(); 
         //objacc.Home_Clinic__c = 'fulham'; 
         //objacc.Membership_Level__c = 'Child';
         //objacc.Membership_Type__c = 'MHC GP' ;
         objacc.Quantity__c = '1';
         //objacc.Payment_Frequency__c = 'Annual';
         //objacc.Billing_Address__c = 'Member';
         //objacc.ContactId__c = cont.id; 
         objacc.Contract_Sent_Date__c = system.Today();
         //objacc.Total_Monthly_Membership_Fee__c = 1000;
         objacc.Membership_Change_Dates__c = system.Today();
         
         objacc.LastName = 'fulham'; 
         objacc.Date_of_Birth__c = system.Today();
         objacc.Gender__c = 'Male' ;
         objacc.Patient_Type__c = 'New'; 
         insert objacc ;
         Account acc = new Account(Id = objacc.Id);
         objacc.Signature__c = 'Member';
         objacc.Signature_Date__c = system.Today();
         update objacc;
         ContentVersion ContentVer = new ContentVersion();
        ContentVer.Title = 'My Doc';
        ContentVer.ContentUrl= 'test.com';
        Insert ContentVer;
        // Create a ContentDocumentLink
        ContentDocumentLink ContentDL = new ContentDocumentLink();
        ContentDL.ContentDocumentId = [SELECT Id, ContentDocumentId FROM ContentVersion WHERE Id =: ContentVer.Id].ContentDocumentId;
        ContentDL.LinkedEntityId = objacc.id;
        ContentDL.ShareType='V';
        Insert ContentDL;
        // Retrieve ?
        ContentDL = [SELECT Id,ShareType FROM ContentDocumentLink WHERE Id =:ContentDL.Id];
        System.debug('Troll ' + ContentDL.ShareType);
        // Verify the share type is = i
        System.assertEquals('V',ContentDL.ShareType);
        
         PageReference pageRef = Page.MembershipContractPreview;
         pageRef.getParameters().put('id',objacc.id);
         ApexPages.StandardController sc = new ApexPages.StandardController(objacc);
         
         //Test.setCurrentPageReference(pageRef);
         memC.init();
         memC.onUpdate();
         memC.sendAndUploadContract();
        
        Test.stopTest();
   }
   
 }
Best Answer chosen by Pintu Budakoti
mirkimirki
Hi,

Generally it is better to assign the query results from SELECT statement into a list of corresponding type. If the query does not match any rows in the database and you try to assign it into a single object (e.g. Account instead of List<Account>) it will result in the exception you described. In your case, the query that you are executing does not provide any results. Either modify the handling of the query results or ensure that your test class creates (and sees) all the data required in order to get the correct behavior.

Regards,
Miika

All Answers

mirkimirki
Hi,

Generally it is better to assign the query results from SELECT statement into a list of corresponding type. If the query does not match any rows in the database and you try to assign it into a single object (e.g. Account instead of List<Account>) it will result in the exception you described. In your case, the query that you are executing does not provide any results. Either modify the handling of the query results or ensure that your test class creates (and sees) all the data required in order to get the correct behavior.

Regards,
Miika
This was selected as the best answer
Pintu BudakotiPintu Budakoti
Thanks for the revert mirki
As i do not want to make changes to the controller please help me with the alternative solution if possible.
mirkimirki
Can you provide the full stack trace for the issue? I'd like to know exactly what line of code / query produces this exception.
Pintu BudakotiPintu Budakoti
I am having issue with the soql part of init() method. I am higlighting that oart of code.

public void init(){
        string objSobject = '';
        objects = new list<string>();
        objAccount = [select Name,Patient_Type__c ,Quantity__c,Billing_Address__c,List_Of_Members_Covered_By_The_Contract__c,Membership_Start_Date__c ,ContactId__c,Membership_Change_Dates__c,Signature__c,Signature_Date__c,Contract_Sent_Date__c,Total_Monthly_Membership_Fee__c,Home_Clinic__c ,Membership_Type__c ,Membership_Level__c ,Payment_Frequency__c, (Select Id, ContentDocumentId From ContentDocumentLinks order by ContentDocument.CreatedDate DESC limit 1)  from Account where id=:apexpages.currentpage().getparameters().get('token')];
        listMappingWrapper = new list<MappingWrapper>{new MappingWrapper()};
        if(objAccount != null && objAccount.ContentDocumentLinks.size() > 0){
            contractDownloadLink = 'https://dev-myhealthcaretestenv.cs89.force.com/sfc/servlet.shepherd/version/download/'+[SELECT Id FROM ContentVersion WHERE ContentDocumentId=:objAccount.ContentDocumentLinks.get(0).ContentDocumentId limit 1].Id+'?asPdf=false&operationContext=CHATTER';    
        }        
        if(Apexpages.currentPage().getParameters().get('editSelectedObject') == null){ 
            objSobject = selectedSobject ;  
        }else{
            objSobject = Apexpages.currentPage().getParameters().get('editSelectedObject'); 
        } 
    }
mirkimirki
Hi,

In the controller, you are using parameter ’token’ to query the avcount. In the test method, you are not setting ’token’ parameter, but instead you are populating ’id’ parameter. I think you should either populate token parameter in test method or use id prameter in controller. And also use the Test.setCurrentPageReference in orfer to have the parameters in controller.