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
rao venkyrao venky 

trigger

how to find profile name of current user in trigger and how to write the test class for that trigger
sandeep sankhlasandeep sankhla
Hi,
You can use Userinfo.getProfileId();

Thanks,
Sandeep
sandeep sankhlasandeep sankhla
Hi,

If you can share your trigger code then I can guide you to write test class for the trigger..

Thanks
Abhinav MIshraAbhinav MIshra
Id profileId=userinfo.getProfileId();
String profileName=[Select Id,Name from Profile where Id=:profileId].Name;
system.debug('ProfileName'+profileName);

Refer the above code.


Apex Trigger Code Testing

Writing test code to invoke Apex Trigger logic is a requirement, even if you have other tests that cover other aspects of the code called from it, such as utility or library methods in other Apex classes.
As such you must have at least one Apex test perform the require DML operations on the object to invoke the trigger logic, no matter how little code maybe in your trigger.
It is common best practice these days to keep code in your Apex Trigger to a minimum and call out to another Apex class. As such it enables you to test the code in a more detailed and more focused mannor in other tests without having to setup a full data set required to issue DML requests in such tests. It also gives rise to better factoring and encapsulation as your code base grows. This consideration is popular with the TDD methodology.
As has already been commented you need to place test code outside of the trigger, indeed it is not actually possible to put test code in a trigger anyway.

The following is very basic illustration of the above, it strays a little into some best practices on layering and encapsulating logic around objects, but I think is relevant here, as its important to think about all logic.

 
/**
 * Class encapsulates logic relating to the Account object, 
 *   other Account related logic required by VF controllers, batch jobs etc could be placed here
 */
public with sharing class Accounts {    

    public static void onBeforeInsert(List<Account> accounts) { }

    public static void someOtherAccountFunctionality(List<Account> accounts) { }    
} 

trigger AccountTrigger on Account (before insert) {

    // Delegate the trigger work to an Apex class that encapsulates behavior relating to the Account object
    if(Trigger.isInsert)
        Accounts.onBeforeInsert(Trigger.new);
}

@IsTest
private with sharing class AccountsTest {

    private static testmethod testAccountTriggerViaDML()
    {
            // This example is simple, illustrates how to invoke the trigger code via DML (required), 
            //   but can become complex and detract from TDD and more granularly testing of the Accounts class
            Account testAccount = new Account( Name = 'Test Account' );
            insert testAccount;
            testAccount = [select Id, Name from Account where Id = :testAccount.Id];
            System.assertEquals(testAccount.Name, 'Test Account');  
    }

    private static testmethod testAccountsOnInsertDirectly()
    {
            // This example is simple, but illustrates the pattern gives access to the Account class code without going via DML, 
            //   more TDD flexibility here (though must be peformed in conjunction with the above style tests as well)
            Account testAccount = new Account( Name = 'Test Account' );
            Accounts.onBeforeInsert(new List<Account> { testAccount } );
            System.assertEquals(testAccount.Name, 'Test Account');
    }

    private static testmethod testSomeOtherAccountFunctionality()
    {
            // Test a specific method on the Accounts class (this may also be tested via the tests associated with the logic calling it
            //     however in a TDD approach these tests still have a role to test such methods in more detail)
            Account testAccount = new Account( Name = 'Test Account' );
            Accounts.testSomeOtherAccountFunctionality(new List<Account> { testAccount });
            System.assertEquals(testAccount.Name, 'Test Account');
    }
}


If you find the answer helpful please select it as best.
Thanks!
gbu.varungbu.varun
Hi

you can get proile name as:
System.debug([select id, profile.name from user  where id=:userinfo.getUserId()].profile.name);
ManojjenaManojjena
Hi Rao,

If you are not using handler class you can create a static method inside trigger and use below code .

public static string getCurrentUsersProfileName(){
return [SELECT Name FROM profile WHERE id=:UserInfo.getProfileId()].Name;
}
and call where ever required .
Else if you are using handler class you can use above method in class and class With Class Name .

Thanks
Manoj
 
rao venkyrao venky
Please Guide me to write the test class for below code, trigger updatephonenumber on Account (after update) { account acc=trigger.new[0]; list clist=[select id,phone from contact where accountid=:Trigger.new]; for(contact con:clist) { if(con.phone == null || con.phone != null) { con.Phone=acc.phone; } //clist.add(con); } update clist; }
sandeep sankhlasandeep sankhla
Hi Rao,

Use below test code for this..

Account objAc = new Account(Name='Test', phone= 121212);
Insert objAc;

Contact objContact = new Conatct(LastName = 'test', AccountId = objAc.Id);
insert objContact ;

Account objA = new Account(Id=objAc.Id, name='tt');
update objA ;


Thanks
Sandeep
 
sandeep sankhlasandeep sankhla
Hi Rao,

Also if your functionalty is to update all contacts when account is updated then use below code for the saem..
 
trigger updatephonenumber on Account (after update) {

List<Contact> lstContactsToUpdate = new List<Contact>();

for(contact con: [select id,phone from contact where accountid IN Trigger.new.keyset()]) 
 {

	if(con.phone == null || con.phone != null) {
	
	con.Phone=trigger.newMap.get(con.AccountId).Phone; 
	lstContactsToUpdate.add(con);
	}
	
 }
 if(!lstContactsToUpdate.isEmpty()) 
	update lstContactsToUpdate; 
 
 }