+ Start a Discussion
Soundar Raj PonpandiSoundar Raj Ponpandi 

Facing an issue in Test Class - Script-thrown exception

Hello,

I am facing following issue in test class, can you please check and let me know the accurate solution for that.


User-added image


Here i have attached a actual class and test class.

Test class
_________________
 
@isTest
public class GD_QuoteApprovalController_Test {
    
    public static testmethod void coverQuoteApprovalController(){
        User adminUser=[Select id from user where isActive=true and profile.name='System Administrator' limit 1];
        Id deptAccountRecordTypeId = Schema.SObjectType.Account.getRecordTypeInfosByName().get('Department').getRecordTypeId();
            
        GD_Organization__c org =  GD_TestDataFactory.createOrganization('TestOrganization', '1234');
        insert org;
        
        Account acc = GD_TestDataFactory.createCustomer('Test Account', 'Customer');
        acc.GD_Organization__c = org.Id;
        acc.RecordtypeId=deptAccountRecordTypeId;
        insert acc;
        
        GD_Department__c dept = GD_TestDataFactory.createDepartment(org.Id, 'Medical Equipment');
        dept.GD_Department_Admin__c = userinfo.getUserId();
        insert dept;
        
         GD_Business_Unit__c businessUnit = GD_TestDataFactory.createBusinessUnit(dept.Id, 'GD_ME_SURGERY');
        insert businessUnit;
        system.debug('businessUnit'+businessUnit.Name);
        Opportunity opp = GD_TestDataFactory.createOpportunity('Test Opportunity', 'Project', 'Proposal', System.today().adddays(5), acc.Id);
        opp.GD_Expected_Revenue__c = 1000;
        insert opp;
        
        GD_Quote__c quotee = GD_TestDataFactory.createQuote(opp.Id,'Price List','Class A');
        quotee.GD_Business_Unit__c = businessUnit.Id;
        insert quotee; 
        quotee=[Select id,GD_Business_Unit__c,CreatedById,GD_Skip_Coorinator_approval__c,GD_Sales_Coordinator__c,GD_Sales_Rep__c,name from GD_Quote__c where id=:quotee.id];
        system.debug('businessUnitquotee. '+quotee.GD_Business_Unit__c);
        Test.startTest();
        GD_QuoteApprovalController.getQuoteDetails(quotee.Id);
        //string comment = 'Please Approve';
        GD_QuoteApprovalController.submitForApproval(quotee, 'Please Approve');
        Test.stopTest();
        
    }
}

Actual Class
_______________
public without sharing class  GD_QuoteApprovalController {
    
    @AuraEnabled
    public static GD_Quote__c getQuoteDetails(String quoteId){
        try{
            GD_Quote__c quote = new GD_Quote__c();
            quote = [SELECT Id,GD_Status__c,GD_Quote_Name__c,OwnerId,GD_Quote_Margin__c,GD_Warranty_Years__c,GD_Has_FOC__c,GD_Quote_Approval_Status__c,
                     GD_Business_Unit__c,GD_Business_Unit__r.Name,GD_Total_In_AED__c,GD_Sales_Rep__r.ManagerId,CreatedById
                     FROM GD_Quote__c WHERE Id=: quoteId ];
            
            User dvisionManager = [SELECT Id,Name,profile.name FROM User WHERE profile.name = 'GD ME Division Manager' LIMIT 1];
            User loggedInUser = [SELECT Id,Name,profile.name FROM User WHERE Id=:userInfo.getUserId()];
            User createdBy = [SELECT Id,Name,profile.name FROM User WHERE Id=: quote.CreatedById];
            string loggedIn = loggedInUser.profile.name;
            string createdByProfile = createdBy.profile.name;
            List<User> approvalUsers = new List<User>();
            
            quote.GD_Division_Manager__c = dvisionManager.Id;
            quote.GD_Sales_Manager__c = quote.GD_Sales_Rep__r.ManagerId;
            //Submitted By Sales Coordinator
            if(loggedIn.contains('Coordinator')){
                quote.GD_Sales_Coordinator__c = loggedInUser.Id;
            }else if(createdByProfile.contains('Coordinator')){
                quote.GD_Sales_Coordinator__c = quote.CreatedById;
            }else{
                quote.GD_Sales_Coordinator__c = loggedInUser.Id;
            }
            
            update quote;
            return quote;
        }catch(Exception e){
            throw new AuraHandledException(e.getMessage());    
        }
    }
    
    @AuraEnabled
    public static InitData submitForApproval(GD_Quote__c quoteRecord,String approvalComments){
        
        boolean Process_success;
        InitData init = new InitData();
        try{
            
            User loggedInUser = [SELECT Id,Name,profile.name FROM User WHERE Id=:userInfo.getUserId()];
            string loggedIn = loggedInUser.profile.name;
            User createdBy = [SELECT Id,Name,profile.name FROM User WHERE Id=: quoteRecord.CreatedById];
            string createdByProfile = createdBy.profile.name;
            
            /* Created By SalesRep & Submitted By Sales Rep*/
            if(!loggedIn.contains('Coordinator') /*&& !createdByProfile.contains('Coordinator')*/){
                quoteRecord.GD_Skip_Coorinator_approval__c = True;
            }
            
            update quoteRecord;
            
            List<Approval.ProcessSubmitRequest> approvalRequestList = new List<Approval.ProcessSubmitRequest>();
            String approverId;
            
            Approval.ProcessSubmitRequest req1 = new Approval.ProcessSubmitRequest();
            req1.setComments(approvalComments);
            req1.setObjectId(quoteRecord.Id); 
            req1.getSubmitterId(); 
            req1.getNextApproverIds();
            approvalRequestList.add(req1);
            system.debug('approvalRequestList.size() ****' + approvalRequestList.size());
            if(approvalRequestList.size() >0){
                 Savepoint sp = Database.setSavepoint();
                List<Approval.ProcessResult> resultList = Approval.process(approvalRequestList);   
                //Approval.process(approvalRequestList);
                
                for(Approval.ProcessResult results: resultList ){  
                    if(results.getInstanceStatus() != 'Rejected'){
                        system.debug('*** Success ***');
                        Approval.ProcessWorkitemRequest req = new Approval.ProcessWorkitemRequest();
                        Approval.ProcessWorkitemRequest req2 = new Approval.ProcessWorkitemRequest();
                        
                        id submitterId;
                        for(ProcessInstanceWorkitem pItem : [Select p.Id,p.ActorId,p.ProcessInstance.SubmittedById from ProcessInstanceWorkitem p where p.ProcessInstance.TargetObjectId =: quoteRecord.Id]){
                            submitterId=pItem.ProcessInstance.SubmittedById;
                            req.setWorkitemId(pItem.Id);
                        }
                        if(submitterId!=null){
                            list<User> userDetails =[SELECT Id, Name, Profile.Name, UserRole.Name FROM User where Id=:submitterId];
                            /*Created By && Submitted By same user (Sales Coordinator) */
                            if(createdByProfile == 'GD ME Sales Coordinator' && submitterId == quoteRecord.GD_Sales_Coordinator__c){
                                req.setComments('Approving request for ' + quoteRecord.Name);
                                req.setAction('Approve'); 
                                Approval.ProcessResult result = Approval.process(req);
                                
                                /*Created By && Submitted by same user (Sales Rep )*/
                            } else if(createdByProfile == 'GD ME Sales Rep' && submitterId == quoteRecord.GD_Sales_Rep__c){
                                system.debug('Entered *** Sales Rep');
                                req.setComments('Approving request for ' + quoteRecord.Name);
                                req.setAction('Approve'); 
                                Approval.ProcessResult result = Approval.process(req); 
                                
                                /*Created By Sales Coordinator && Submitted Sales Rep */   
                            }else if(createdByProfile == 'GD ME Sales Coordinator' && submitterId == quoteRecord.GD_Sales_Rep__c){
                                system.debug('Entered As expected ****');
                                List<Approval.ProcessWorkitemRequest> allReq = new List<Approval.ProcessWorkitemRequest>(); 
                                req.setComments('Approving request for ' + quoteRecord.Name);
                                req.setAction('Approve'); 
                                allReq.add(req);
                                Approval.ProcessResult result = Approval.process(req);
                                boolean coordApproved = true;
                                
                                /*Cannot approve two records at same time, So set a dummy boolean as coordApproved*/
                                if(coordApproved = true){
                                    for(ProcessInstanceWorkitem pItem1 : [Select p.Id,p.ActorId,p.ProcessInstance.SubmittedById from ProcessInstanceWorkitem p where p.ProcessInstance.TargetObjectId =: quoteRecord.Id]){
                                        submitterId=pItem1.ProcessInstance.SubmittedById;
                                        req2.setWorkitemId(pItem1.Id);
                                    }
                                    req2.setComments('Approving request for ' + approvalComments);
                                    req2.setAction('Approve'); 
                                    allReq.add(req2);
                                    Approval.ProcessResult result1 = Approval.process(req2);
                                }
                                
                                /*Set<Id> qtIds = (new Map<Id, GD_Quote__c>([SELECT Id FROM GD_Quote__c where id =: quoteRecord.Id])).keySet();
Set<Id> pIds = (new Map<Id, ProcessInstance>([SELECT Id,Status,TargetObjectId FROM ProcessInstance where TargetObjectId in :qtIds])).keySet();
Set<Id> pInstanceWorkitems = (new Map<Id, ProcessInstanceWorkitem>([SELECT Id,ProcessInstanceId FROM ProcessInstanceWorkitem WHERE ProcessInstanceId in :pIds limit 2])).keySet();
system.debug('pInstanceWorkitems ****' + pInstanceWorkitems);
for (Id pInstanceWorkitemsId:pInstanceWorkitems){
system.debug(pInstanceWorkitemsId);
Approval.ProcessWorkitemRequest req2 = new Approval.ProcessWorkitemRequest();
req2.setComments('Approving request for ' + quoteRecord.Name);
req2.setAction('Approve'); //to approve use 'Approve'
//req2.setNextApproverIds(new Id[] {UserInfo.getUserId()});
// Use the ID from the newly created item to specify the item to be worked
req2.setWorkitemId(pInstanceWorkitemsId);
// Add the request for approval
allReq.add(req2);
}
Approval.ProcessResult[] result2 =  Approval.process(allReq);*/
                            }
                        }
                        system.debug('*** Process Pass ***');
                        init.Process_success = true;
                        //Process_success = true;
                    }else {
                       /*Got Auto Rejected - Here Empty the quote approval status and delete process instance*/
                        Database.rollback(sp);
                        
                        quoteRecord.GD_Quote_Approval_Status__c = '';
                        update quoteRecord;
                        init.Process_success = false;
                        
                        
                        
                        
                    }
                }
                
                
            }
            else{
                system.debug('**** Not Met ****');
            }
            
        }catch(Exception e){
            system.debug('EXCEPTION ******* '+e.getStackTraceString());
            throw new AuraHandledException(e.getMessage());    
        }
        system.debug('init ***' + init);
        return init;
    }
    
    
     Public class InitData{
        @Auraenabled public Boolean Process_success;
        public InitData(){
            Process_success = false;
        }
    }
    
    
}

Thannks in advance.

Regards,
Soundar.
 
Best Answer chosen by Soundar Raj Ponpandi
AnudeepAnudeep (Salesforce Developers) 
Soundar - I found similar issue reported here. I believe it is related