+ Start a Discussion
JN22JN22 

Test Class to Populate Account ID

Hello,

I have a custom object (Contract_Summary__c) that has a Master-Detail with Opportunity.  I have created a test class to test a trigger and I'm trying to populate the Account Name field on my Contract_Summary__c from the Opportunity field.  Can anyone give me the syntax to do this?  My code from the test class is below and Line 4 is where I'm having trouble:

public static Contract_Summary__c createContSumm(Id oppId){ 
        Contract_Summary__c ContSumm = new Contract_Summary__c();
            ContSumm.Related_Opportunity__c = oppId;
            ContSumm.Account_Name__c = oppId.AcctId.id;
            ContSumm.Current_Effective_Date__c = date.newinstance(2025,1,31);
            ContSumm.Current_Expiration_Date__c = date.newinstance(2027,1,31);
            ContSumm.Type_of_Contract__c = 'Initial MSA';
            ContSumm.Client_Signature_Date__c = date.newinstance(2025,1,31);
        return ContSumm;


Best Answer chosen by JN22
Prafull G.Prafull G.
Your method argument is only Id whereas you are trying to access Account Id associated with Opportunity. You either need to pass Opportunity object or need to do SOQL in this method to get Account Id. 
Like
public static Contract_Summary__c createContSumm(Opportunity opp){ 
        Contract_Summary__c ContSumm = new Contract_Summary__c();
            ContSumm.Related_Opportunity__c = opp.Id;
            ContSumm.Account_Name__c = opp.AccountId;
            .
            .
            .
OR
public static Contract_Summary__c createContSumm(Id oppId){ 
        Id actId = [SELECT AccountId FROM Opportunity WHERE Id=:oppId].AccountId;
        Contract_Summary__c ContSumm = new Contract_Summary__c();
            ContSumm.Related_Opportunity__c = oppId;
            ContSumm.Account_Name__c = actId;
            .
            .

Hope this will give you an idea to proceed.

Cheers!

All Answers

Prafull G.Prafull G.
Your method argument is only Id whereas you are trying to access Account Id associated with Opportunity. You either need to pass Opportunity object or need to do SOQL in this method to get Account Id. 
Like
public static Contract_Summary__c createContSumm(Opportunity opp){ 
        Contract_Summary__c ContSumm = new Contract_Summary__c();
            ContSumm.Related_Opportunity__c = opp.Id;
            ContSumm.Account_Name__c = opp.AccountId;
            .
            .
            .
OR
public static Contract_Summary__c createContSumm(Id oppId){ 
        Id actId = [SELECT AccountId FROM Opportunity WHERE Id=:oppId].AccountId;
        Contract_Summary__c ContSumm = new Contract_Summary__c();
            ContSumm.Related_Opportunity__c = oppId;
            ContSumm.Account_Name__c = actId;
            .
            .

Hope this will give you an idea to proceed.

Cheers!
This was selected as the best answer
JN22JN22
Great, thanks!  That did the trick!