function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
ImmuImmu 

Test Class for Trigger(Iam new to test class)

Hi

Iam new to test class...Iam struggling to write test class to my trigger...

 

Here is my Trigger

trigger ownershipTrigger on Account (before update) {
Map<Id,Account> mp=new Map<Id,Account>();
mp=trigger.oldMap;
for(account a:trigger.new)
{
Account al=new Account();
al=mp.get(a.Id);
if(a.Ownership!=al.Ownership)
{
a.ownership.adderror('You Cannot Change this Ownership');
}
}
}

 

Any help would be greatly appreciated!!! 

jiah.choudharyjiah.choudhary

Hi @Immu,

 

For the trigger to fire, you just have to create records in test class which would satisfy your trigger conditions. As in here, Since it is a before update on Account,

 

1. Create an Account record.

2. Update the same record with a different Owner.

 

Just a rough idea:

1. Account objAccount = new Account(Name = 'testAccount', Owner = UserInfo.getUserId());

    insert objAccount;

2. Create New User record in the same test class.

3. objAccount.OwnerId = 'instance of user id created in previous step(step 2)'.

     update objAccount.

 

Hope this helps

 

ImmuImmu

Hi Choudhary..

   

Thanks for replying...

 

If possible send in code syntax

 

 

jiah.choudharyjiah.choudhary

@Immu,

 

@isTest(SeeAllData=true) //Using SeeAllData=true since there is a query on profile.
private class TestClass
{
    static testmethod  void AccountTriggerTestClass()
    {
        Account objAccount = new Account(Name = 'Test Account 1');
        insert objAccount;
        
        Profile platformUser = [select id from Profile where Name = 'Some profile' LIMIT 1];
        
        User objUser = new User( FirstName = 'Test',LastName  = 'User', Email = 'test@test.com', Username  = 'noname@test.com',ProfileId = platformUser.Id,
                                Alias = 'Mr.', TimeZoneSidKey = 'America/New_York', EmailEncodingKey = 'ISO-8859-1',
                                LocaleSidKey = 'en_US', LanguageLocaleKey = 'en_US');
        insert objUser;
        
        objAccount.OwnerId = objUser.Id;
        update objAccount;
    }
}

 

Please try and hit kudos if it solved your query.