You need to sign in to do that
Don't have an account?
Tina Chang 6
How to Write Test Class for Accounts with or without Opportunities?
Hello, I wrote the following test class for my Apex code "LastModifiedOppty" but it didn't work with code coverage 0%. Does anyone know how to fix this? My apologies I have just started the coding portion of my Salesforce knowledge base, so any advice would be much appreciated! Thank you!
@isTest private class LastModifiedOpptyTest { @isTest static void createAccountWithOpp() { // Accounts with Opportunities Account accts = new Account(); accts.Name = 'testAccount'; Insert accts; Opportunity opp = new Opportunity(); opp.Name = 'testOpportunity'; opp.StageName = 'Prospecting'; opp.CloseDate = Date.today(); opp.AccountId = accts.Id; opp.Amount = 100000; Insert opp; Test.startTest(); System.assertEquals(1, accts.Opportunities.Size()); Test.stopTest(); } @isTest static void createAccountWithoutOpp() { // Accounts without Opportunities Account accts2 = new Account(); accts2.Name = 'testAccount2'; Insert accts2; Test.startTest(); System.assertEquals(0, accts2.Opportunities.Size()); Test.stopTest(); } }Here's my Apex class "LastModifiedOppty":
public class LastModifiedOppty { public static void updateLastOpptyIdField() { // Retrieve the last modified opportunity's ID for each account. Account[] accountList = [SELECT Id, (SELECT Id, Amount from Opportunities ORDER BY LastModifiedDate DESC LIMIT 1) FROM Account]; // to access the opportunity related to individual account and pass the Id value on to the Last_Opportunity_ID__c field. // if the account does not have any opportunities, pass the value 'Without Oppty' to the Last_Opportunity_ID__c field. for(Account acct : accountList){ if(acct.Opportunities.size()>0){ Opportunity relatedOpp = acct.Opportunities[0]; acct.Last_Opportunity_ID__c = relatedOpp.Id; acct.Last_Opportunity_Amount__c = relatedOpp.Amount; } else if(acct.Opportunities.size()==0){ acct.Last_Opportunity_ID__c = 'Without Oppty'; } } update accountList; } }
All Answers
Please check once below sample code :
Hope this helps you!
If my answer helps resolve your query, please mark it as the 'Best Answer' & upvote it to benefit others.
Thanks
Varaprasad
@For Support: varaprasad4sfdc@gmail.com
Modified Test Class: