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
nikkeynikkey 

How to call n no of USER profiles and add error method in test class

Can any one help me out. How to call 'n' no of USER profiles  and add error method in test class.In the trigger i do have users other than those users it should throw an error.so how do i use the users and the add error message in test classAny help very much appreciated.
Trigger :
trigger oli_multiple_products_before_insert on OpportunityLineItem (before insert) {

 Id userProfileId = userinfo.getProfileId();
  String userProfileName = [SELECT ID, Name from Profile Where Id = : userProfileId].Name;


  if( userProfileName != 'System Administrator' &&
      userProfileName !='Custom Marketing Users 10K 25K '&&
      userProfileName !='Customer Service User'&&
      userProfileName !='Fulfillment User'
     ) {


    for (OpportunityLineItem oli : Trigger.new) {
        if (Trigger.isInsert) {



            Integer line_Count = [SELECT COUNT()
                                    FROM OpportunityLineItem o
                                    WHERE o.OpportunityId = :oli.OpportunityId
                                    AND o.PriceBookEntryId = :oli.PriceBookEntryId  ];

            if (line_Count > 0) {
                oli.addError('A Product can not be added more than once to the Opportunity.');
         }                    
        }
    }
  }
 }
TestClass :
@isTest
    private class Oli_multiple_Products_TestClass{
    static testmethod void ValidateOlimultipleproducts(){
    Date closeDt = Date.Today();

//Find user with Profile = Sales and Service
        Profile SalesNService = [Select id from Profile where Name = 'Sales and Service' limit 1];
        User u = new User(
            Alias = 'standt', 
            Email='standarduser@testorg.com',
            EmailEncodingKey='UTF-8',
            LastName='Testing',
            LanguageLocaleKey='en_US',
            LocaleSidKey='en_US',
            ProfileId = SalesNService.Id,
            TimeZoneSidKey='America/Los_Angeles',
            UserName='standarduser@testorg.com'
        );


    Account acc = new Account (Name ='TestClassAccountOpportunitySegment', Region__c = 'AM', Persona__C = 'Artisan');
    //System.debug('AccountOpportunitySegment before insert of new Account: ' + acc.segment__C);
    insert acc;

    Opportunity opp = new opportunity (Name ='TestclassAccountOpportunitySegment', AccountId= acc.Id, StageName = 'Prospecting', 
                                       CloseDate = closeDt, ForecastCategoryName = 'Pipeline');
    insert opp;                                 

    OpportunityLineItem ooli = new OpportunityLineItem (Quantity=2, OpportunityId=opp.Id, TotalPrice=10, PriceBookEntryId='01ud0000004YWFqAAO');
    insert ooli;

    OpportunityLineItem ooli1 = new OpportunityLineItem (Quantity=2, OpportunityId=opp.Id, TotalPrice=10, PriceBookEntryId='01ud0000004YWFzAAO');
    insert ooli1;

    }
    }



 
Best Answer chosen by nikkey
Anupam RastogiAnupam Rastogi
Hi Nikkey,

I have removed the redundant lines. Check now, and place an appropriate profile name in the query.
@isTest
private class Oli_multiple_Products_TestClass{
    static testmethod void ValidateOlimultipleproducts(){
        
        Profile p = [SELECT Id FROM Profile WHERE Name='Standard User']; 
        User u = new User(Alias = 'standt', Email='salesnsvc123@abcorg.com', EmailEncodingKey='UTF-8', LastName='Testing', LanguageLocaleKey='en_US', LocaleSidKey='en_US', ProfileId = p.Id, TimeZoneSidKey='America/Los_Angeles', UserName='salesnsvc3214@torg.com');
        
        System.runAs(u) {
            Date closeDt = Date.Today();
            
            Account acc = new Account (Name ='TestClassAccountOpportunitySegment', Region__c = 'AM', Persona__C = 'Artisan');
            //System.debug('AccountOpportunitySegment before insert of new Account: ' + acc.segment__C);
            insert acc;
            
            Opportunity opp = new opportunity (Name ='TestclassAccountOpportunitySegment', AccountId= acc.Id, StageName = 'Prospecting', 
                                               CloseDate = closeDt, ForecastCategoryName = 'Pipeline');
            insert opp;                                 
            
            OpportunityLineItem ooli = new OpportunityLineItem (Quantity=2, OpportunityId=opp.Id, TotalPrice=10, PriceBookEntryId='01ud0000004YWFqAAO');
            insert ooli;
            
            OpportunityLineItem ooli1 = new OpportunityLineItem (Quantity=2, OpportunityId=opp.Id, TotalPrice=10, PriceBookEntryId='01ud0000004YWFzAAO');
            try{
                insert ooli1; 
            }
            catch(Exception e) {
                Boolean exceptionThrown = e.getMessage().contains('A Product can not be added more than once to the Opportunity.')? true : false;
                System.assertEquals(exceptionThrown, true);
            }
        }
    }
}

Thanks
AR

If you find the reply useful that solves your problem then please mark it as best answer.

 

All Answers

Anupam RastogiAnupam Rastogi
Hi Nikkey,

Here are the changes you can do to your test class to perform the required checks - 

1. User Profile Check - To execute the Trigger for a particular user profile you need to use runAs() method. So you need to place all your test class code within the System.runAs() method as shown below.
2. addError check - To check for the proper execution of error messages that you have coded in the Trigger, you need to use try/catch and assertEquals() method as shown below. Basically place all code in try that will throw the error.
@isTest
private class Oli_multiple_Products_TestClass{
    static testmethod void ValidateOlimultipleproducts(){
        
        Profile p = [SELECT Id FROM Profile WHERE Name='Sales and Service']; 
        User u = new User(Alias = 'standt', Email='salesnsvc123@abcorg.com', EmailEncodingKey='UTF-8', LastName='Testing', LanguageLocaleKey='en_US', LocaleSidKey='en_US', ProfileId = p.Id, TimeZoneSidKey='America/Los_Angeles', UserName='salesnsvc3214@torg.com');
        
        System.runAs(u) {
            Date closeDt = Date.Today();
            
            //Find user with Profile = Sales and Service
            Profile SalesNService = [Select id from Profile where Name = 'Sales and Service' limit 1];
            User u = new User(
                Alias = 'standt', 
                Email='standarduser@testorg.com',
                EmailEncodingKey='UTF-8',
                LastName='Testing',
                LanguageLocaleKey='en_US',
                LocaleSidKey='en_US',
                ProfileId = SalesNService.Id,
                TimeZoneSidKey='America/Los_Angeles',
                UserName='standarduser@testorg.com'
            );
            
            Account acc = new Account (Name ='TestClassAccountOpportunitySegment', Region__c = 'AM', Persona__C = 'Artisan');
            //System.debug('AccountOpportunitySegment before insert of new Account: ' + acc.segment__C);
            insert acc;
            
            Opportunity opp = new opportunity (Name ='TestclassAccountOpportunitySegment', AccountId= acc.Id, StageName = 'Prospecting', 
                                               CloseDate = closeDt, ForecastCategoryName = 'Pipeline');
            insert opp;                                 
            
            OpportunityLineItem ooli = new OpportunityLineItem (Quantity=2, OpportunityId=opp.Id, TotalPrice=10, PriceBookEntryId='01ud0000004YWFqAAO');
            insert ooli;
            
            OpportunityLineItem ooli1 = new OpportunityLineItem (Quantity=2, OpportunityId=opp.Id, TotalPrice=10, PriceBookEntryId='01ud0000004YWFzAAO');
            try{
                insert ooli1; 
            }
            catch(Exception e) {
                Boolean exceptionThrown = e.getMessage().contains('A Product can not be added more than once to the Opportunity.')? true : false;
                System.assertEquals(exceptionThrown, true);
            }
        }
    }
}

Thanks
AR

If you find the reply useful that solves your problem then please mark it as best answer.
nikkeynikkey
Hi Anupam Rastogi ,

Thanks for your reply.

In the code i could see the user and profile are given twice.
it throws an Error as
Error Message	System.QueryException: List has no rows for assignment to SObject
Stack Trace	Class.Oli_multiple_Products_TestClass.ValidateOlimultipleproducts: line 6, column 1
Error line no :Profile p = [SELECT Id FROM Profile WHERE Name='Sales and Service'];
 
Anupam RastogiAnupam Rastogi
Hi Nikkey,

I have removed the redundant lines. Check now, and place an appropriate profile name in the query.
@isTest
private class Oli_multiple_Products_TestClass{
    static testmethod void ValidateOlimultipleproducts(){
        
        Profile p = [SELECT Id FROM Profile WHERE Name='Standard User']; 
        User u = new User(Alias = 'standt', Email='salesnsvc123@abcorg.com', EmailEncodingKey='UTF-8', LastName='Testing', LanguageLocaleKey='en_US', LocaleSidKey='en_US', ProfileId = p.Id, TimeZoneSidKey='America/Los_Angeles', UserName='salesnsvc3214@torg.com');
        
        System.runAs(u) {
            Date closeDt = Date.Today();
            
            Account acc = new Account (Name ='TestClassAccountOpportunitySegment', Region__c = 'AM', Persona__C = 'Artisan');
            //System.debug('AccountOpportunitySegment before insert of new Account: ' + acc.segment__C);
            insert acc;
            
            Opportunity opp = new opportunity (Name ='TestclassAccountOpportunitySegment', AccountId= acc.Id, StageName = 'Prospecting', 
                                               CloseDate = closeDt, ForecastCategoryName = 'Pipeline');
            insert opp;                                 
            
            OpportunityLineItem ooli = new OpportunityLineItem (Quantity=2, OpportunityId=opp.Id, TotalPrice=10, PriceBookEntryId='01ud0000004YWFqAAO');
            insert ooli;
            
            OpportunityLineItem ooli1 = new OpportunityLineItem (Quantity=2, OpportunityId=opp.Id, TotalPrice=10, PriceBookEntryId='01ud0000004YWFzAAO');
            try{
                insert ooli1; 
            }
            catch(Exception e) {
                Boolean exceptionThrown = e.getMessage().contains('A Product can not be added more than once to the Opportunity.')? true : false;
                System.assertEquals(exceptionThrown, true);
            }
        }
    }
}

Thanks
AR

If you find the reply useful that solves your problem then please mark it as best answer.

 
This was selected as the best answer
nikkeynikkey
Anupam Rastogi ,

Now it got executed but the code coverage is coming to 90% only.When checked in the Developer Console the "ADDERROR" line is not

getting covered in the trigger code.Any help very much appreciated.
Anupam RastogiAnupam Rastogi
Hi Nikkey,

I guess because the Trigger is based on 'before insert' event therefore it is not able to find any created Line Items.

Try changing the trigger to 'after insert' and check results.

Thanks
AR

If you find the reply useful that solves your problem then please mark it as best answer.
 
nikkeynikkey
Anupam Rastogi ,

Thanks for your time and needful help.
nikkeynikkey
Anupam Rastogi I have used the profile name as "'Standard User' in the test class and moved into production. Will it effect. Since 'Standard User' is a Standard profile.
Anupam RastogiAnupam Rastogi
You can use a profile that is used by your org and runs the test successfully.