+ Start a Discussion
Selim BEAUJOURSelim BEAUJOUR 

Write an Apex trigger that modifies Account fields before inserting records.

Hi all,

I have a problem with this challenge : 

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.

and this is my classes :
 
public class AccountTriggerHandler {
    
    public static void CreateAccounts(List<Account> acclist){
        
        
        for(Account a:acclist){
            
            if(a.ShippingState!=a.BillingState){
                a.BillingState=a.ShippingState;
              
            }
        }
    }

}
 
trigger AccountTrigger on Account (before insert) 
{
    if (Trigger.isBefore && Trigger.isInsert) {
			AccountTriggerHandler.CreateAccounts(Trigger.new);
		}	
	}
 
@isTest
public class AccountTriggerTest {
    
    @isTest static void TestCreate200Records(){
        
        // Test Setup data
        // Create 200 new Accounts
        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 acct;
        	Test.stopTest();
            
            for (Account a:accts){
                
                System.assertEquals('CA', a.ShippingState, 'ERROR');
            }
            
    }

        
}
}
And this error :
Challenge Not yet complete... here's what's wrong: 
The 'AccountTrigger' Trigger does not appear to be working correctly. Inserted records did not have matching BillingState and ShippingState values.

Anyone can help me please??
Thanks!
 
Best Answer chosen by Selim BEAUJOUR
Abhishek_DEOAbhishek_DEO
As per my understanding, you should place "a.ShippingState"(in CreateAccounts method) on left side as per requirement mentioned.

Fr eg,
a.ShippingState = a.BillingState;

Please let me know if it helps.

All Answers

Abhishek_DEOAbhishek_DEO
As per my understanding, you should place "a.ShippingState"(in CreateAccounts method) on left side as per requirement mentioned.

Fr eg,
a.ShippingState = a.BillingState;

Please let me know if it helps.
This was selected as the best answer
Selim BEAUJOURSelim BEAUJOUR
Thank you! My class test doesn't work but the challenge is completed
Andrew EversleyAndrew Eversley
Hello, Abhishek_DEO, Selim Beaujour,

I'm having the same issue pertaining to this same challenge. I've included my coding below for the Account Trigger on Account object .

I'm not clear on where the Shipping State = a.BillingState should be included in the method. Could you, or someone, clarify for me. Thanx

User-added image
Joel RamosJoel Ramos
Hi Andrew, It was for me hard to complete the challenge.

AccountTriggerHandler is the class that has the "business logic". For this reason, you have to include the comparison in this method or class.

AccountTrigger occurs when a new account is created and is bind with the business logic class. I see this execirse / triggers in this way.
Verma, ManishVerma, Manish
Hi,

Here is the Apex class:
 
public class AccountTriggerHandler 
{
    public static void CreateAccounts(List<Account> acclist)
    {
        for(Account account : acclist)
        {
            if(account.ShippingState!=account.BillingState)
            {
                account.ShippingState = account.BillingState; // you need to update ShippingState
            }
        }
    }
}

And trigger code is as below:
 
trigger AccountTrigger on Account (before insert) 
{
    if (Trigger.isBefore && Trigger.isInsert) {
			AccountTriggerHandler.CreateAccounts(Trigger.new);
		}	
}

Hope this helps!!
Kishore Kumar MuniswamyKishore Kumar Muniswamy
In Test Class Line 14  remove the //   Comment you will compile
Kishore Kumar MuniswamyKishore Kumar Muniswamy
Selim BEAUJOUR  Your Code is perfect just remove the comment tags thats all
Jihane MessoudiJihane Messoudi
Hi, I'm beginner in Apex and I don't know how you use the "System.assertEquals('CA', a.ShippingState, 'ERROR');" in the Apex test Class
Could someone clarify please? Thanks
Justin DeckJustin Deck
Hi, I'm having a similar issue on this module. I am receiving the following error:

The 'AccountTrigger' Trigger does not appear to be working correctly. Inserted records did not have matching BillingState and ShippingState values

My account trigger code is:

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


My Account Trigger Test code is:

@isTest

public class AccountTriggerTest {

    @isTest static void TestCreate200Records(){


        // Test Setup data

        // Create 200 new Accounts

        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 acct;

            Test.stopTest();

            for (Account a:accts){

                System.assertEquals('CA', a.ShippingState, 'ERROR');

            }
 
    }

}
 
}

My Account Trigger Handler code is:

public class AccountTriggerHandler 

{

    public static void CreateAccounts(List<Account> acclist)

    {

        for(Account account : acclist)

        {

            if(account.ShippingState!=account.BillingState)

            {

                account.ShippingState  = account.BillingState = 'CA';
        }
    }
    }
}


Please help. I'm really stuck on this one! My Account Trigger seems to be the same as the example above - not sure what I'm missing here. I definitely executed the Run Alll Tests before trying to complete the challenge.

Thanks,
Justin
sravani adirajusravani adiraju
Developer console > Run all tests ---- > solved my issue with the challange 
M ParnellM Parnell
Why do I keep getting this error message when running all test from the developer console:
System.AssertException: Assertion Failed: ERROR: Expected: CA, Actual: null

There are currently no Account/Customer records in my instance. I deleted them all for testing purposes of this Apex class.
samyuktha reddy etikayalasamyuktha reddy etikayala
The 'AccountTrigger' Trigger does not appear to be working correctly. Inserted records did not have matching BillingState and ShippingState values.
Anyone can help me, please??
 Thanks in advance.

Thanks and regards,
Samyuktha.

 
Shauryanaditya SinghShauryanaditya Singh
Hi M Parnell... I get the same error. Please Help.
Banshi LalBanshi Lal
I am getting the same error as @M Parnell 
System.AssertException: Assertion Failed: ERROR: Expected: CA, Actual: null
Sahil Bhandekar 4Sahil Bhandekar 4
Try Bellow Code
public class AccountTriggerHandler {
    
     public static void CreateAccounts (List<Account> accList)
     {
         for(Account acc : accList)
         {
             if(acc.ShippingState!=acc.BillingState)
             {
                 acc.ShippingState = acc.BillingState;
             }
         }
     }

}
 
trigger AccountTrigger on Account (before insert) 
{
    if (Trigger.isBefore && Trigger.isInsert) {
			AccountTriggerHandler.CreateAccounts(Trigger.new);
		}	
	}
 
@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();
        System.assertEquals(200, [SELECT Count() FROM Account WHERE ShippingState = 'CA' ]);
    }
}

 
Nagaraju Mogili 15Nagaraju Mogili 15
Hi All,
Even I am also getting the error, while doing this excercise, Please find the below screenshot for your refereceUser-added image

Can anyone help me why I am getting this error
Bruno Souza 7Bruno Souza 7
Hey Guys I understand the code how it is working, but I always wonder what this line below does, Could anyone please explain to me:?

for(Account a:acclist){

I have seen it in several examples in Trailhead but I still don't know what is this for.

Tks in advance,
Vijay Singh 105Vijay Singh 105
Class 
public class AccountTriggerHandler {
 public static void CreateAccounts(List<Account> acclist)
    {
        for(Account account : acclist)
        {
            if(account.ShippingState!=account.BillingState)
            {
                account.ShippingState = account.BillingState; // you need to update ShippingState
            }
        }
    }
}

Test Class 
@isTest
public class AccountTriggerTest {
@isTest static void TestCreate200Records(){
        
        // Test Setup data
        // Create 200 new Accounts
        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();
            List<Account> verifyAccts = [SELECT id FROM Account WHERE ShippingState = 'CA' ];
           System.assertEquals(200, verifyAccts.size());
            
    

        
}
}
Please let me know if it helps.
Bhagyashri PawarBhagyashri Pawar
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'm getting this error.
Bhagyashri PawarBhagyashri Pawar
Hi, Selim BEAUJOUR
I am getting this error for your code.
any suggestions please.
Muhammad Saad JavedMuhammad Saad Javed
Hello guys, for those of you whose trigger problem is returning from trailhead, they need to do as following, as per chalenge we are told to match shipping state with billing state, while most of student are matching billing state with shipping state.

if(a.ShippingState!=a.BillingState){

                a.ShippingState=a.BillingState;

               

            }
Mitesh Patel 85Mitesh Patel 85
This is my solution that worked 100% 
public class AccountTriggerHandler {
    public static void CreateAccounts(List<Account> acclist)
    {
        for(Account acc:acclist)
        {
            if(acc.ShippingState!=acc.BillingState)
            {
                acc.ShippingState = acc.BillingState;
            }
        }
    }
}
 
trigger AccountTrigger on Account (before insert) 
{
    if (Trigger.isBefore && Trigger.isInsert) 
    {
            AccountTriggerHandler.CreateAccounts(Trigger.New);
    }   
}
 
@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();            
            System.assertEquals(200, [SELECT Count() FROM Account WHERE ShippingState = 'CA' ]);            
	}
}

Note: Remember that after creating the Test case in Developer Consol go to Test -> Run All and than only submit on the Trail Head.
Subendu TiwariSubendu Tiwari
nice it worked well. i had an issue with assertEquals part. but this method clearly worked well
Lay Durafe 22Lay Durafe 22

Hi All, here is the solution:

trigger AccountTrigger on Account (before insert) {
    if (Trigger.isBefore && Trigger.isInsert) {
        AccountTriggerHandler.CreateAccounts(Trigger.New);
    }
}
 
public class AccountTriggerHandler {
    public static void CreateAccounts(List<Account> accts){
        for(Account a : accts){
            if(a.ShippingState != a.BillingState){
                a.ShippingState = a.BillingState;
            }
        }
    }
}
 
@isTest
private class AccountTriggerTest {
    @isTest static void TestAccountValidationInBulk(){
        
        // test setup data + create 200 new accounts
        List<Account> accts = new List<Account>();
        for(Integer i = 0; i < 200; i++){
            Account acct = new Account();
            acct.Name = 'Test Account' + i;
            acct.BillingState = 'CA';
            accts.add(acct);
        }
        
        // perform test
        Test.startTest();
        insert accts;
        Test.stopTest();
        
        // verify 200 accts inserted + check ShippingState = CA
        List<Account> verifyAccts = [SELECT Id FROM Account];
        System.assertEquals(200, verifyAccts.size());
        System.assertEquals(200, [SELECT Count() FROM Account
                                  WHERE ShippingState = 'CA']);
        
    }
}

+ Bruno Souza 7

for(Account a:acclist){ ... } represents a for-each loop - this is used to loop through elements in an array. 

A for-each loop has the following syntax:
for (type variableName : arrayName) {
  // code to be executed
}

In our case we are looping for-each Account (type) from the List of Accounts collection (array). 

Hope this helps!
Parikshit SarkarParikshit Sarkar
Here is my solution with 100% code coverage :

Apex class - 
 
public class AccountTriggerHandler {
    public static List<Account> CreateAccounts(List<Account> thisAcc){
        List<Account> a = new List<Account>(); 
        for(Account acc : thisAcc){
            if(acc.ShippingState != acc.BillingState ){
                acc.ShippingState = acc.BillingState;
                a.add(acc);
            } 
        }
        return a; 
    }
}


Apex Trigger - 

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

Apex Test Class - 
 
@isTest
	public class AccountTriggerTest {
        public static List<Account> createTestData(){
            List<Account> accList = new List<Account>(); 
            for(integer i=0 ; i<200; i++){
                Account acc = new Account(Name='Test account '+i, 
                                          BillingState = 'CA');
                accList.add(acc);
            }
            insert accList; 
            
            return accList;
            
        }
        
		@isTest
        public static void testCreateAccounts(){
			List<Account> thisAcc = createTestData(); 
            Test.startTest(); 
            AccountTriggerHandler.CreateAccounts(thisAcc);
            Test.stopTest();
            List<Account> accList = [Select Id, Name, BillingState, ShippingState From Account limit 200]; 
            
            System.assertEquals(200, accList.size()); 
            
        }
}

Regards,
Parikhit Sarkar.
Muhammad Adil JavedMuhammad Adil Javed
Hi All, try this solution (100% Working):

Apex class:
public class AccountTriggerHandler {
	public static void CreateAccounts(List<Account> accts) { 
        for (Account acct : accts) {  
            if(acct.ShippingState!=acct.BillingState){
                acct.ShippingState=acct.BillingState; 
            } 
        } 
    }
}

Apex Trigger:
trigger AccountTrigger on Account (before insert, before update, before
    delete, after insert, after update, after delete,  after undelete) {
    if (Trigger.isBefore && Trigger.isInsert) {
        AccountTriggerHandler.CreateAccounts(Trigger.New);
    }
}
Apex Test Class:
@isTest
private class AccountTriggerTest {
    @isTest static void TestCreateNewAccountInBulk() {
        // Test Setup data
        // Create 200 new Accounts
        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);
        }              
        // Perform Test
        System.Test.startTest();
        insert accts;                               
        System.Test.stopTest();
        // Verify that 200 new Accounts ShippingState=CA
        List<Account> insertedAccounts = [SELECT ShippingState from Account];
        for (Account a:insertedAccounts){ 
			System.assertEquals('CA', a.ShippingState,'ERRER'); 
        }                            
    }
}




 
Aamir Ahmad 1Aamir Ahmad 1
@isTEst
private class AccountTriggerTest 
{
    @isTest static void CreateAccountsTest()
    {
        List<Account> accounts = new List<Account>();
        for(Integer i=1; i<=200; i++)
        {
            accounts.add(new Account(Name='Account'+i, BillingState='CA'));
        }
        Test.startTest();
            insert accounts;
        Test.stopTest();

        accounts = [select ShippingState, BillingState, Name from Account];        
        for(Account a : accounts)
        {
            System.assertEquals('CA',a.ShippingState);
        }
    }
}

For those who are getting this error is assert statement
"System.AssertException: Assertion Failed: ERROR: Expected: CA, Actual: null"

You need to re-query the account records to get the  updated values.