+ Start a Discussion
Andrew EversleyAndrew Eversley 

Understanding Execution Context - Apex trigger Trailhead Issue.

Hello Community,

I'm having an issue with this particular challenge below: 

Write an Apex trigger that fires before records are inserted and ensures that the ShippingState field has the same value as the BillingState field.
Create an Apex class named AccountTriggerHandler that contains a public static method called CreateAccounts to accept the List of Account objects.
For each Account record, before saving, ensure that the ShippingState field has the same value as the BillingState field.
Write an Apex trigger named AccountTrigger that fires before records are inserted.
The Apex trigger must call the AccountTriggerHandler.CreateAccounts() method with the collection of new records.
Create a test class named AccountTriggerTest that inserts 200 Account records with a BillingState of CA. After the insert, test to ensure that all 200 records have a ShippingState of CA.
Before verifying this challenge, run your test class at least once using the Developer Console Run All feature.

This is my Challenge Error:

Challenge Not yet complete... here's what's wrong: 
The Trigger 'AccountTrigger' does not appear to be calling the AccountTriggerHandler class correctly or using isBefore or isInsert content variables.

These are my codings below :
AccountTriggerHandler
User-added image

AccountTrigger - Trigger On Account Object
User-added image

AccountTriggerTest
User-added image

P.S. I'm pretty new to the developing with Apex so I'm learning and growing so the help is appreciated community. 
Best Answer chosen by Andrew Eversley
Amit Chaudhary 8Amit Chaudhary 8
Hi Andrew ,
Please check below post for Test class level change also.
1) https://developer.salesforce.com/forums/ForumsMain?id=906F0000000DBLFIA4

1) AccountTrigger  Trigger
trigger AccountTrigger on Account (before insert) 
{
    if (Trigger.isBefore && Trigger.isInsert) 
   {
 	AccountTriggerHandler.CreateAccounts(Trigger.new);
   }	
}
2) AccountTriggerHandler Apex class.
public class AccountTriggerHandler 
{
    public static void CreateAccounts(List<Account> acclist)
    {
        for(Account a:acclist)
        {
            if(a.ShippingState!=a.BillingState)
            {
                a.ShippingState = a.BillingState; // you need to update ShippingState
            }
        }
    }
}
3) AccountTriggerTest Test class.
@isTest
public class AccountTriggerTest {
    
    @isTest static void TestCreate200Records()
    {
        List<Account> accts = new List<Account>();
        for(Integer i=0; i < 200; i++) 
        {
            Account acct = new Account(Name='Test Account ' + i, BillingState = 'CA');
            accts.add(acct);
        }
        
        Test.startTest();
            insert accts ;
        Test.stopTest();
        // Please query all record once again to check assert
        List<Account> lstAccount = [select ShippingState from Account];
        for (Account a: lstAccount )
        {
            System.assertEquals('CA', a.ShippingState, 'ERROR');
        }
        
    }
}

Please let me know if this will help you

Thanks
Amit Chaudhary

 

All Answers

Amit Chaudhary 8Amit Chaudhary 8
Please update your AccountTrigger and add "Trigger.isBefore".
AccountTrigger - Trigger On Account Object

If(Trigger.isBefore && Trigger.isInsert)
{

}
trigger AccountTrigger on Account (before insert) 
{
    if (Trigger.isBefore && Trigger.isInsert) {
			AccountTriggerHandler.CreateAccounts(Trigger.new);
		}	
	}

Please check below post for same issue. I hope that will help you.
1) https://developer.salesforce.com/forums/?id=906F0000000DBRhIAO
2)


NOTE: When adding code please use the "Add a code sample" button (icon <>) to increase readability and make it easier to reference.

Let us know if this will help you
Andrew EversleyAndrew Eversley
Thanx Amit, I will let you know. Appreciate the note on the code sample as well for future postings. 
Amit Chaudhary 8Amit Chaudhary 8
Hi Andrew ,
Please check below post for Test class level change also.
1) https://developer.salesforce.com/forums/ForumsMain?id=906F0000000DBLFIA4

1) AccountTrigger  Trigger
trigger AccountTrigger on Account (before insert) 
{
    if (Trigger.isBefore && Trigger.isInsert) 
   {
 	AccountTriggerHandler.CreateAccounts(Trigger.new);
   }	
}
2) AccountTriggerHandler Apex class.
public class AccountTriggerHandler 
{
    public static void CreateAccounts(List<Account> acclist)
    {
        for(Account a:acclist)
        {
            if(a.ShippingState!=a.BillingState)
            {
                a.ShippingState = a.BillingState; // you need to update ShippingState
            }
        }
    }
}
3) AccountTriggerTest Test class.
@isTest
public class AccountTriggerTest {
    
    @isTest static void TestCreate200Records()
    {
        List<Account> accts = new List<Account>();
        for(Integer i=0; i < 200; i++) 
        {
            Account acct = new Account(Name='Test Account ' + i, BillingState = 'CA');
            accts.add(acct);
        }
        
        Test.startTest();
            insert accts ;
        Test.stopTest();
        // Please query all record once again to check assert
        List<Account> lstAccount = [select ShippingState from Account];
        for (Account a: lstAccount )
        {
            System.assertEquals('CA', a.ShippingState, 'ERROR');
        }
        
    }
}

Please let me know if this will help you

Thanks
Amit Chaudhary

 
This was selected as the best answer
Andrew EversleyAndrew Eversley
Thank you for your imput Amit Chaudhary. Your suggestion above worked out for me. I appreciate your prompt responses and your assistance. Thanks.
Martina PastorkovaMartina Pastorkova
Challenge Not yet complete... here's what's wrong: 
The 'AccountTriggerHandler' class did not achieve 100% code coverage via your test methods. Make sure that you chose 'Run All' tests in the Developer Console at least once before attempting to verify this challenge.

I have followed the above mentioned steps here, however, this error keeps coming up:
Challenge Not yet complete... here's what's wrong: 
The 'AccountTriggerHandler' class did not achieve 100% code coverage via your test methods. Make sure that you chose 'Run All' tests in the Developer Console at least once before attempting to verify this challenge.

Any idea what could be wrong?  Thank you.
prathyusha kolanuprathyusha kolanu
Hi I am trying to follow this Module, https://trailhead.salesforce.com/modules/apex_basics_dotnet/units/execution_context but it throws duplicate error when i execute from Execute anonymous method. Any help is appreciated.
Line: 6, Column: 1
System.DmlException: Insert failed. First exception on row 0; first error: DUPLICATES_DETECTED, Use one of these records?: []
public with sharing class AccountHandler {
    public static void CreateNewOpportunity(List<Account> accts) {
        for (Account a : accts) {
            Opportunity opp = new Opportunity();
            opp.Name = a.Name + 'Opportunity';
            opp.AccountId = a.Id;
            opp.StageName = 'Prospecting';
            opp.CloseDate = System.Today().addMonths(1);
            insert opp;
        }
    }
}
 
trigger AccountTrigger on Account (before insert, before update, before
    delete, after insert, after update, after delete,  after undelete) {
    if (Trigger.isAfter && Trigger.isInsert) {
        AccountHandler.CreateNewOpportunity(Trigger.New);
    }
}
 
Account acct = new Account(
    Name='Test Account 4',
    Phone='(415)555-9090',
    NumberOfEmployees=31,
    BillingCity='San Francisco1');
insert acct;

 
Chinni Krishna VallabhapurapuChinni Krishna Vallabhapurapu
For future visitors of this page - Refer Amit Chaudhary's scripts above with one exception.
replace this line of code -- If(Trigger.isBefore && Trigger.isInsert)
with If(Trigger.isBefore || Trigger.isInsert)
Instead of "and" operator for isBefore and isInsert one should use "or" operator.
Danny PhamDanny Pham
Hello,
 I got error

Error:
 Class.AccountHandler.CreateNewOpportunity: line 16, column 1

Stack Trace:
 Class.AccountHandler.CreateNewOpportunity: line 16, column 1 Trigger.AccountTrigger: line 3, column 1

Here is my trigger test:
@isTest
private class AccountTrigger_Test {
   @isTest static void TestCreateNewAccountInBulk () {
       //Test Setup data
       //Create 200 new account
       List<Account> accts = new List<Account>();
       for(Integer i=0; i < 200; i++){
           Account acct = new Account(Name='Test Account ' + i);
           accts.add(acct);
       }

       //Perform Test
       Test.startTest();
       insert accts;
       Test.stopTest();

       //Verify that 200 new accounts were inserted
       List<Account> verifyAccts = [SELECT Id FROM Account];
       System.assertEquals(200, verifyAccts.size());

       //Also verify that 200 new Opportunity were inserted
       List<Opportunity> verifyOpps = [SELECT Id FROM Opportunity];
       System.assertEquals(200, verifyOpps.size());
   }
}

 
Nassim BenkiraneNassim Benkirane

Hello, if you have an issue with:

The 'AccountTriggerHandler' class did not achieve 100% code coverage via your test methods. Make sure that you chose 'Run All' tests in the Developer Console at least once before attempting to verify this challenge.

Add a second test methode that the ShippingState is different from BillingState.

here is the AccountTriggerTest test classe:

@isTest
public class AccountTriggerTest {
    
    @isTest static void TestCreate200Records()
    {
        List<Account> accts = new List<Account>();
        for(Integer i=0; i < 200; i++) 
        {
            Account acct = new Account(Name='Test Account ' + i, BillingState = 'CA');
            accts.add(acct);
        }
        
        Test.startTest();
            insert accts ;
        Test.stopTest();
        // Please query all record once again to check assert
        List<Account> lstAccount = [select ShippingState from Account];
        for (Account a: lstAccount )
        {
            System.assertEquals('CA', a.ShippingState, 'ERROR');
        }
    }
        
        @isTest static void TestCreatedifferentState()
    {
        List<Account> accts = new List<Account>();
        for(Integer i=0; i < 100; i++) 
        {
            Account acct = new Account(Name='Test Account ' + i, BillingState = 'sCA');
            accts.add(acct);
        }
        
        Test.startTest();
            insert accts ;
        Test.stopTest();
        // Please query all record once again to check assert
        List<Account> lstAccount = [select ShippingState from Account];
        for (Account a: lstAccount )
        {
            System.assertEquals('CAh', a.ShippingState, 'ERROR');
        }
        
    }
}
Shubham Kashyap 27Shubham Kashyap 27

@Amit Chaudhary

Hi Amit,

I followed the same code that you mentioned above, but I am getting error and not able to figure out what is causing this.

Please help me out.

Challenge not yet complete in shubham.kashyap1@tcs.com
There was an unexpected error in your org which is preventing this assessment check from completing: System.DmlException: Insert failed. First exception on row 0; first error: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY, AccountTrigger: execution of BeforeInsert caused by: System.SObjectException: SObject row was retrieved via SOQL without querying the requested field: Account.ShippingState Class.AccountTriggerHandler.CreateAccounts: line 22, column 1 Trigger.AccountTrigger: line 5, column 1: []



Thanks,
Shubham

Sandeep Khandelwal 26Sandeep Khandelwal 26
Hello,

I have read the post where almost everyone has use System.assertEquals('CA', a.ShippingState, 'ERROR');  as the way to verify the 200 Accounts with CA as billing state.
I have written in little different way and I guess that can be accepted as well.

My code here
User-added image
Subhendu Roy 6Subhendu Roy 6
Thanks, It worked.