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
Alex KirbyAlex Kirby 

INVALID_CROSS_REFERENCE_KEY, Owner ID:

Hi All,

I am having trouble getting past this error in a test class as far as I can see th owners are all set correctly.

Class:
 
public with sharing class PdfGeneratorController {

    Private final Credit_Check__c CC;    
    public PdfGeneratorController (ApexPages.StandardController stdController) {
                                           this.CC= (Credit_check__c)stdController.getrecord();
                                           
                                
}
        
  
  public PageReference savePdf() {

  List<credit_check__c> aK = [Select id, opportunity__c,opportunity_2__c, opportunity_3__c
                                From credit_check__c where id=:cc.id Limit 1];
      
     	id U1 = RtypesUtil.getObjectRecordTypeId(Credit_check__c.SObjectType, 'In Progress Under 1GWh');
        id B1A10 = RtypesUtil.getObjectRecordTypeId(Credit_check__c.SObjectType, 'In Progress 1-10GWh');
        id O10 = RtypesUtil.getObjectRecordTypeId(Credit_check__c.SObjectType, 'In Progress Over 10GWh');
        id Ex = RtypesUtil.getObjectRecordTypeId(Credit_check__c.SObjectType, 'In Progress Export');
        id Es = RtypesUtil.getObjectRecordTypeId(Credit_check__c.SObjectType, 'In Progress Energy Solutions');
        id Ar = RtypesUtil.getObjectRecordTypeId(Credit_check__c.SObjectType, 'Display Atradius Results');  
      
       	id U1C = RtypesUtil.getObjectRecordTypeId(Credit_check__c.SObjectType, 'Closed Under 1GWh');
        id B1A10C = RtypesUtil.getObjectRecordTypeId(Credit_check__c.SObjectType, 'Closed 1-10GWh');
        id O10C = RtypesUtil.getObjectRecordTypeId(Credit_check__c.SObjectType, 'Closed Over 10GWh');
        id ExC = RtypesUtil.getObjectRecordTypeId(Credit_check__c.SObjectType, 'Closed Export');
        id EsC = RtypesUtil.getObjectRecordTypeId(Credit_check__c.SObjectType, 'Closed Energy Solutions');

        string opp2 = string.valueof(ak[0].get('opportunity_2__c'));
        string opp3 = string.valueof(ak[0].get('opportunity_3__c'));

    PageReference pdf = new PageReference('/apex/cvs_pdf?id='+apexpages.currentpage().getparameters().get('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.getcontentAsPDF();


    // need to pass unit test -- current bug    
    } catch (VisualforceException e) {
        body = Blob.valueOf('Some Text'+ e);
    }

    attach.Body = body;
    // add the user entered name
    attach.Name = cc.name+'.pdf';
    attach.IsPrivate = false;
    //attach.ContentType='PDF';
    // attach the pdf to the account
    attach.ParentId = string.valueof(ak[0].get('opportunity__c'));
     
    insert attach;
    
    if(opp2 !=NULL){
    Attachment attach2 = new Attachment();

    // the contents of the attachment from the pdf
    Blob body2;

    try {

        // returns the output of the page as a PDF
        body2 = pdf.getcontentAsPDF();


    // need to pass unit test -- current bug    
    } catch (VisualforceException e) {
        body2 = Blob.valueOf('Some Text'+ e);
    }

    attach2.Body = body2;
    // add the user entered name
    attach2.Name = cc.name+'.pdf';
    attach2.IsPrivate = false;
    //attach.ContentType='PDF';
    // attach the pdf to the account
    attach2.ParentId = opp2;
     
    insert attach2;
    }
    if(opp3 !=NULL){
    Attachment attach3 = new Attachment();

    // the contents of the attachment from the pdf
    Blob body3;

    try {

        // returns the output of the page as a PDF
        body3 = pdf.getcontentAsPDF();


    // need to pass unit test -- current bug    
    } catch (VisualforceException e) {
        body3 = Blob.valueOf('Some Text'+ e);
    }

    attach3.Body = body3;
    // add the user entered name
    attach3.Name = cc.name+'.pdf';
    attach3.IsPrivate = false;
    //attach.ContentType='PDF';
    // attach the pdf to the account
    attach3.ParentId = opp3;
     
    insert attach3;
    }
    if(cc.recordtypeid == Ar){
          if(cc.cc_type__c == '<1GWh'){
                cc.recordtypeid = U1C;
                cc.Status__c = 'Closed';
                cc.ownerid = cc.CreatedById;
            }
            Else If (cc.cc_type__c == '1GWh to 10GWh'){
                cc.recordtypeid = B1A10C;
                cc.Status__c = 'Closed';
                cc.ownerid = cc.CreatedById;
            }
            Else If (cc.cc_type__c == '>10Gwh'){
                cc.recordtypeid = O10C;
                cc.Status__c = 'Closed';
                cc.ownerid = cc.CreatedById;
            }
            Else If (cc.cc_type__c == 'Export'){    
                cc.recordtypeid = ExC;
                cc.Status__c = 'Closed';
                cc.ownerid = cc.CreatedById;
            }
            Else If (cc.cc_type__c == 'Energy Solutions'){
                cc.recordtypeid = EsC;
                cc.Status__c = 'Closed';
                cc.ownerid = cc.CreatedById;
            }
        
      cc.Ownerid = cc.CreatedById; 
      cc.date_of_credit_check__c = Date.valueof(system.now()); 
      cc.cc_completed__c = system.now();
      cc.Status__c = 'Closed';
      
                  
      update cc;
        
    }
      
      
            
    
    // send the user to the account to view results
    //return new PageReference('/'+ string.valueof(ak[0].get('opportunity__c')));
    
     return new PageReference('javascript:window.close()'); 

  }

}

Test Class:
 
@isTest
public class Test_PdfGeneratorController {
    
    static User testUser;
    
    static testmethod void testPdfGenerator(){   
        test.startTest();
        id Ar = RtypesUtil.getObjectRecordTypeId(Credit_check__c.SObjectType, 'Display Atradius Results');
        
        //Select Active user
        user usr = [select name, id from user where IsActive=true and profile.name='Indirect Sales Support Analyst' limit 1];
        
        CreateAccOpp.CreateOppty();
        
		List<Account> accs = [Select id, ownerid From Account Limit 1];
        Id Acc = accs.get(0).Id;  
        
        List<Opportunity> opps = [SELECT id, number_of_meters__c, ownerid FROM Opportunity Limit 1];
        Id Opp = opps.get(0).Id;
		       
        Credit_Check__c CC = new Credit_Check__c();
            CC.Company__c = Acc;
            CC.Credit_Check_Type__c = 'Acquisition';
            CC.Ownerid = system.UserInfo.getuserid();
        	cc.opportunity__c = opp;
        	cc.Opportunity_2__c = opp;
            cc.opportunity_3__c = opp;
            CC.Requested_Payment_Days__c = '21';
            CC.Requested_Payment_Method__c = 'BACS';
            cc.Requested_Payment_Days_2__c = '21';
            cc.Requested_Payment_Method_2__c = 'BACS';
            cc.Requested_Payment_Days_3__c = '21';
            cc.Requested_Payment_Method_3__c = 'BACS';
            CC.Approval_Status__c = 'Approved without Conditions';
            CC.Date_of_Credit_Check__c = System.today();
            CC.Experian_No_Score__c = TRUE;
            CC.Experian_No_Credit_Limit__c = TRUE;
            CC.Atradius_Buyer_Rating__c = 30;
            CC.Credit_Pricing_Check__c = TRUE;
            CC.Has_Full_Insurance__c = 'Yes';
            CC.Payment_Days__c = '21';
            CC.Payment_Method__c = 'Direct Debit';
            CC.Payment_Days_2__c = '21';
            CC.Payment_Method_2__c = 'Direct Debit';    
            CC.Payment_Days_2__c = '21';
            CC.Payment_Method_2__c = 'Direct Debit';   
            CC.Payment_Performance_Score_Unavailable__c = TRUE;
            CC.Maximum_Contract_End_Date__c = System.today()+10;
            CC.Atradius_Buyer_Rating__c = null;
            CC.Atradius_Buyer_Rating_Unavailable__c = TRUE;
            CC.Atradius_Credit_Insurance_Limit__c = null;
            CC.Experian_No_Score__c = FALSE;
            CC.Experian_No_Credit_Limit__c = FALSE;
            CC.Experian_Score__c = 30;
            CC.Experian_Credit_Limit__c = 1000;
            cc.RecordTypeId = Ar;
       insert CC;
 
      //cc.Cp_From_CC__c = true;
      // update cc;
        System.debug('Account OwnerId - '+  accs.get(0).ownerid);
		System.debug('Opportunity OwnerId - '+ opps.get(0).ownerid);
        System.debug('Credit Check OwnerId - '+  cc.ownerid);
        
      // List<Credit_Check__c> ccs = [Select id, opportunity__c, opportunity_2__c, opportunity_3__c From Credit_check__c Limit 1];
      // Id ccId = ccs.get(0).Id;
      // id opp1 = ccs.get(0).opportunity__c;
      // id opp2 = ccs.get(0).opportunity_2__c;
      // id opp3 = ccs.get(0).opportunity_3__c;
        
      // for(Credit_Check__c cc : ccs){
          	
          cc.cc_type__c ='1GWh to 10GWh';
        cc.ownerid = system.UserInfo.getUserId();
          update cc;
            
           cc.cc_type__c ='>10Gwh';
        cc.ownerid = system.UserInfo.getUserId();
           update cc;
            
           cc.cc_type__c ='Export';
        cc.ownerid = system.UserInfo.getUserId();
           update cc;
            
           cc.cc_type__c ='Energy Solutions';
        cc.ownerid = system.UserInfo.getUserId();
           update cc;
            
            //set pdf visualforce page
            PageReference pref = Page.CVS_PDF;
            //set VF page id
            pref.getParameters().put('id',cc.id);
            Test.setCurrentPage(pref);
            
            //create and link visualforce page standard controller and pdf generator extension
            ApexPages.StandardController con1 = new ApexPages.StandardController(cc); 
            PdfGeneratorController con = new PdfGeneratorController(con1);
            
            // submit the record        
            pref = con.savePdf();
            
            // assert that they were sent to the correct page
            system.assertEquals(pref.getUrl(), 'javascript:window.close()');
            
            // assert that an attachment exists for the record
            //System.assertEquals(1,[select count() from attachment where parentId = :opp1 limit 1]);
            //System.assertEquals(1,[select count() from attachment where parentId = :opp2 limit 1]);
            //System.assertEquals(1,[select count() from attachment where parentId = :opp3 limit 1]);
            test.stopTest();
            
        }
        
    }
Debug log sample:


21:15:53.287 (4287509289)|DML_BEGIN|[148]|Op:Update|Type:Credit_Check__c|Rows:1 21:15:53.299 (4299084067)|DML_END|[148] 21:15:53.299 (4299208664)|VF_PAGE_MESSAGE|Owner ID: owner cannot be blank 21:15:53.299 (4299285408)|EXCEPTION_THROWN|[148]|System.DmlException: Update failed. First exception on row 0 with id a0me00000027BnDAAU; first error: INVALID_CROSS_REFERENCE_KEY, Owner ID: owner cannot be blank: [OwnerId] 21:15:53.300 (4300317592)|SYSTEM_MODE_EXIT|false 21:15:53.300 (4300340110)|METHOD_EXIT|[96]|01pe0000000450V|PdfGeneratorController.savePdf() 21:15:53.300 (4300394260)|FATAL_ERROR|System.DmlException: Update failed. First exception on row 0 with id a0me00000027BnDAAU; first error: INVALID_CROSS_REFERENCE_KEY, Owner ID: owner cannot be blank: [OwnerId]

Help is appreciated, thanks all
CyberJusCyberJus
The CreatedById is not set until the record is inserted, so you are trying to set the OwnerId to null in lin 119, 124, etc. By default the Owner will be set to the CreatedById, so you dont really need to specify that.