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
Amrik DasAmrik Das 

Help With Test Class for Trigger with Profile ID

Need help to generate test class for the following trigger.

 

trigger RestrictCreate on Opportunity (before insert, before update) 
{
    //List<Account> lstAcc = [select name from account where type='Distributor' and SSS_SAP_ID_Actual__c LIKE '008%'];
    for(Opportunity opp : Trigger.new)
    {
        System.debug('Account = ' + opp.Account);
        System.debug('oppty = ' + opp);
        System.debug('Oppty.Account.Type = ' + opp.Account.type);
        System.debug('SAP ID ACtual = ' + opp.Account.SSS_SAP_ID_Actual__c);
        Account test = [select id,name,type,SSS_SAP_ID_Actual__c from account where id=:opp.accountId];
        System.debug(test);
        Id profileId=userinfo.getProfileId();
        if(profileId != '00e30000000i9fA')
        {
            if((test.type=='Distributor') && (test.SSS_SAP_ID_Actual__c.startsWith('008')))
            opp.addError('Can not link Opportunity with Account of Type Distributor & SAP ID Actual starting with 008');
            return;
        }
    }
}

ManojjenaManojjena
HI Amrik,
Your trigger has some issues in coding .Basically you should not hard code id which you have hard coded while checking profile .
Also you have query inside for loop which will give you error on mass insert or update .

For test class basically you need to insert Account if SSS_SAP_ID_Actual__c is not a look up field .if it is a look up field then you need to insert that record first then account with type other then Distributor ,in on emore test method with Distributor . then opportunity .You need to query from profile then create user an dexecute test with run as that user then your test class will work .
Check below link and try to write test class also try to optimise your trigger code .
http://manojjena20.blogspot.in/2015/06/tips-and-tricks-for-test-class.html

Let me  know you need any help !!
Thanks
Manoj