+ Start a Discussion
Fei YangFei Yang 

Give your question a title...

I'm a greener of Apex development.

I'm now creating a Trigger Test Class. The class is to create a new Account, and then create a Opportunity for the Account.

My problem is, after creating Account and Opportunity, I could not get Account by soql query. Can anyone help this?

My code and Execution log as below:

@isTest
public with sharing class TriggerTest_InvoiceItemUpdate {
    static testMethod void myUnitTest()
    {
        test.startTest();
            List<Account> accounts = new List<Account>{};
            List<Opportunity> opportunities = new List<Opportunity>{};
            String AccountId, OpportunityID;
       
         //Create a new Account
            Account testAccount = new Account(Name='Account_Test');
            accounts.add(testAccount);
            insert accounts; 
            AccountId = accounts[0].id;
       
         //Create a new Opportunity
            Opportunity Opportunity_test= new Opportunity(Account = accounts[0], Name='Opportunity_Test', StageName='Close Won', CloseDate=date.newInstance(2011, 7, 4));
            opportunities.add(Opportunity_test);
            insert opportunities;
            OpportunityID=opportunities[0].id;
            system.debug('1>>>'+opportunities[0].Account.id);
        
         //To querry the Opportunity's Account
         opportunities =[select id, account.name  from Opportunity where id=: OpportunityID];
         system.debug('2>>>'+opportunities[0]);
         system.debug('3>>>'+opportunities[0].account.name);
       
        test.stopTest();
        }
}



Execution log:
[21]|DEBUG|1>>>001N000000ACdfjIAD
[25]|DEBUG|2>>>Opportunity:{Id=006N0000003BzKOIA0}
[26]|DEBUG|3>>>null
Best Answer chosen by Fei Yang
Subramani_SFDCSubramani_SFDC
Try like this..it will help...

Opportunity Opportunity_test= new Opportunity(AccountId= accounts[0].id, Name='Opportunity_Test', StageName='Close Won', CloseDate=date.newInstance(2011, 7, 4));

All Answers

Subramani_SFDCSubramani_SFDC
Try like this..it will help...

Opportunity Opportunity_test= new Opportunity(AccountId= accounts[0].id, Name='Opportunity_Test', StageName='Close Won', CloseDate=date.newInstance(2011, 7, 4));
This was selected as the best answer
Fei YangFei Yang
Thank you, Subramani.

It really helps. May I ask why?