+ Start a Discussion
Kevin TullosKevin Tullos 

Help me write a test class for this... Please...

I got this trigger from the help and I am unable to write a test class for it.  My best attempt did not suffice any of the tests.  Could someone please help me.

thank you.


//Reassigns Contact to Account Owner

trigger reassignContact on Contact (before insert, before update) {
   try {

        Set<Id> accountIds = new Set<Id>();
        Map<Id, Id> accountOwnerIdMap = new Map<Id, Id>();
  
        // all the accounts whose owner ids to look up
        for ( Contact c : Trigger.new ) {
            if(c.accountId <> null){
             accountIds.add( c.accountId );
            }
        }
      
        // look up each account owner id
        for ( Account acct : [ SELECT id, ownerId FROM account WHERE id IN :accountIds ] ) {
            accountOwnerIdMap.put( acct.id, acct.ownerId );
        }
      
        // change contact owner to its account owner
        for ( Contact c : Trigger.new ) {
            if(c.AccountId <> null){
             c.ownerId = accountOwnerIdMap.get( c.accountId );
            }
        }
    } catch(Exception e) { //catch errors
        System.Debug('reassignContacts failure: '+e.getMessage()); //write error to the debug log
    }

}
Best Answer chosen by Kevin Tullos
Developer.mikie.Apex.StudentDeveloper.mikie.Apex.Student
Hey, it seems pretty straight forward. You will get sufficient coverage with a test like this:

@isTest
public class TestReassignContact{
    static testMethod void TestReassignContact(){


User use = new User(alias = 'ceo', email='admin@testorg.com',
        emailencodingkey='UTF-8', lastname='Testing', languagelocalekey='en_US',
        localesidkey='en_US', 
        timezonesidkey='America/Los_Angeles', username='adminTas@testorg.com', profileid = Profile1.Id);
        insert use1;
User use = new User(alias = 'ceo2', email='admin2@testorg.com',
        emailencodingkey='UTF-8', lastname='Testing', languagelocalekey='en_US',
        localesidkey='en_US', 
        timezonesidkey='America/Los_Angeles', username='admin2@testorg.com', profileid = Profile1.Id);
        insert use2;
Account acc = new Account(Name = 'Test Trigger', OwnerId = Use1.id);
insert acc;
Contact Con = new Contact(LastName = 'TestTrigger', AccountId = acc.id);
Insert Con;
acc.OwnerId = Use2.id;
Update acc;
con.FirstName = 'TestTriggerAgain';
Update Con;

  
    }
}

This should do the trick.

it may have a few errors, youll just have to try and save and then correct the problems. 

Basically, it adds two user records, an account record and then a contact record.

As the account record has its ownerId set to the first user, the trigger is tested upon insert...then again as the account owner id is changed to the second user, the contact has its firstname updated...this will trigger the update half of the trigger and will change the ownerid accordingly.

If this answer helps you , please mark as best answer.

Thank you

Michael Lomas

All Answers

umesh atryumesh atry
Hi,

This a Trigger. and we dont need to write any test class for trigger.
just try to run your class where this trigger is used. means associated class will auto test this trigger.

Developer.mikie.Apex.StudentDeveloper.mikie.Apex.Student
Hey, it seems pretty straight forward. You will get sufficient coverage with a test like this:

@isTest
public class TestReassignContact{
    static testMethod void TestReassignContact(){


User use = new User(alias = 'ceo', email='admin@testorg.com',
        emailencodingkey='UTF-8', lastname='Testing', languagelocalekey='en_US',
        localesidkey='en_US', 
        timezonesidkey='America/Los_Angeles', username='adminTas@testorg.com', profileid = Profile1.Id);
        insert use1;
User use = new User(alias = 'ceo2', email='admin2@testorg.com',
        emailencodingkey='UTF-8', lastname='Testing', languagelocalekey='en_US',
        localesidkey='en_US', 
        timezonesidkey='America/Los_Angeles', username='admin2@testorg.com', profileid = Profile1.Id);
        insert use2;
Account acc = new Account(Name = 'Test Trigger', OwnerId = Use1.id);
insert acc;
Contact Con = new Contact(LastName = 'TestTrigger', AccountId = acc.id);
Insert Con;
acc.OwnerId = Use2.id;
Update acc;
con.FirstName = 'TestTriggerAgain';
Update Con;

  
    }
}

This should do the trick.

it may have a few errors, youll just have to try and save and then correct the problems. 

Basically, it adds two user records, an account record and then a contact record.

As the account record has its ownerId set to the first user, the trigger is tested upon insert...then again as the account owner id is changed to the second user, the contact has its firstname updated...this will trigger the update half of the trigger and will change the ownerid accordingly.

If this answer helps you , please mark as best answer.

Thank you

Michael Lomas
This was selected as the best answer
pradeep naredlapradeep naredla
Hi kevin,
        For writting a test class first u have to write the trigger in class formate and here is the test class for ur trigger.

@istest
public class classname 
{
public static testmethod void methodname()
{
//first insert a user record
User u = new User();
u.Username= 'mike.white@company.com';
u.Email = 'mike.white@company.com';
u.Lastname = 'mike';
u.Firstname = 'white';
u.Alias = 'mwhite';
u.CommunityNickname = 'mwhite01';
u.UserRole = [ select id from userrole where id ='here enter the hardcore value of a role ' ];
u.Profile = [ select id from profile where id ='here enter the hardcore value of a role ' ];

u.CurrencyIsoCode = 'USD';
u.TimeZoneSidKey = 'GMT';
u.LocaleSidKey = 'en_US';
u.EmailEncodingKey = 'ISO-8859-1';
u.LanguageLocaleKey = 'en_US';
u.UserPermissionsMobileUser = false;
insert u;
set<id> set1= new set<id>();
user u=[select id,username form user where lastname='mike'];//getting the user and adding it to set
set1.add(u.id);

//insert account record

account acc= new account();
acc.name='mike';
acc.ownerid=u.id;
insert acc;

//now insert a contact
contact con= new contact();
con.lastname='mike';
insert con;


hope it will help u

Regards,
pradeep

Kevin TullosKevin Tullos
Thanks everyone!!  I got the first one to work and it gave me 91% coverage.  One tip that i realized...  Use the admin profile.  It makes things a little easier...

btw, pradeep, I could not get your code to run and it was too complex for me to fix.  it looks great though.

thanks.

kevin