+ Start a Discussion
wt35wt35 

Error while testing class:

Hi Community,

 

I get this error while running my test class.

The test class only tests one method by providing an opportunity Id as parameter.

The debug log shows that the Opp Id is well transmitted to the method, 

 but then the SOQL Query against that Opp Id finds no results..

I appreciate your help...Thanks

 

 

Class:

 

 global class CloseDuplicateOpportunities{

   webService static String closeDuplicateOpportunities(Id contextOppId) {
       
        Opportunity contextOpp;
        List<Opportunity> relevantOpps;
        String finalMessage;
        Profile userProfile = [SELECT Name FROM Profile WHERE Id = :Userinfo.getProfileId()];

        Set<String> AuthorizedProfiles = new Set<String>();
        Set<String> AuthorizedOppOwner = new Set<String>();
        Set<String> TargetProducts = new Set<String>();
        AuthorizedProfiles.addAll(GeneralUtil.getCodeVariableCustomSetting('CloseDuplicate_AuthorizedProfiles').split(';'));
        AuthorizedOppOwner.addAll(GeneralUtil.getCodeVariableCustomSetting('CloseDuplicate_AuthorizedOppOwner').split(';'));
        TargetProducts.addAll(GeneralUtil.getCodeVariableCustomSetting('CloseDuplicate_TargetProducts').split(';'));
        
        
        /*********************************************************/
        /*****************AUTHORIZED USER ************************/
        /*********************************************************/
        
        System.debug ('#####################CONTEXTOPP ID: ' + contextOppId);
        try{
        contextOpp = [SELECT Id,AccountId,Owner.Name FROM Opportunity WHERE Id=:contextOppId];
        } catch(Exception e){
        System.debug('The following exception has occurred while trying to get the context opp: ' + e.getMessage());
        }
        
       System.debug ('#####################USERPROFILE NAME: ' + userProfile.Name);
       System.debug ('#####################CONTEXT OPP OWNER NAME: ' + contextOpp.Owner.Name);
        if (  AuthorizedProfiles.contains(userProfile.Name) &&        
                (contextOpp.Owner!=null && AuthorizedOppOwner.contains(contextOpp.Owner.Name)    )  
           )
        {
            List<Opportunity> oppsToUpdate = new List<Opportunity>();
            
            oppsToUpdate.add(contextOpp);
                       
            try{
            relevantOpps = [SELECT Id,StageName,Reason_For_Closed_Lost__c FROM Opportunity WHERE 
                AccountId = :contextOpp.AccountId AND
                IsClosed = false AND
                Owner.Name like 'NA BS User' AND
                Id != :contextOpp.Id AND 
                Product_Target__c IN :TargetProducts
                /*Product_Target__c INCLUDES ('Advanced','Express Checkout Shortcut (ECS)','Pro')*/];
            oppsToUpdate.addAll(relevantOpps);
            } catch(Exception e){
            finalMessage = 'No relevant opportunities have been closed because either none were found or an error has happened.';
            }

            if(oppsToUpdate!=null  &&  oppsToUpdate.size()>0)
            {
                for (Opportunity o : oppsToUpdate)
                {
                 o.StageName = GeneralUtil.getCodeVariableCustomSetting('CloseDuplicate_StageWhenClosing');
                 o.Reason_For_Closed_Lost__c = GeneralUtil.getCodeVariableCustomSetting('CloseDuplicate_ReasonWhenClosing');
                }

                System.debug('###########oppsToUpdate '+ oppsToUpdate);
                try{
                update oppsToUpdate;
                finalMessage = relevantOpps.size() + ' similar opportunities have been closed in addition to this one';
                } catch(Exception e){
                finalMessage = 'No relevant opportunities have been closed';
                }
            }
            
        } 
           


        /*********************************************************/
        /********************NON-AUTHORIZED USER *****************/
        /*********************************************************/
        else{            
            finalMessage = 'No relevant opportunities have been closed because you do not have an authorized profile or the opportunity is not owned by NA BS User.';
        }


     return finalMessage;
    }


}

 

 

 

 

Test Class:

 

@isTest
public class CloseDuplicateOpportunitiesTest {


    static testMethod void test1() {
        
        Opportunity o1;
        Opportunity o2;
        User testUser;
        
        Profile p = [SELECT Id FROM Profile WHERE Name='NA Telesales Rep']; 
        
        /*User oppOwner = new User(LastName='NA BS User', ProfileID=p.Id, Alias = 'standt', Email='standarduser@testorg.com', 
          EmailEncodingKey='UTF-8', LanguageLocaleKey='en_US', 
          LocaleSidKey='en_US', TimeZoneSidKey='America/Los_Angeles', UserName='dwqwdwqdqwdwqdqwefewgfe@testorg.com');
        insert oppOwner;  */
          
        /*User u = new User(ProfileId = p.Id,Alias = 'standt', Email='standarduser@testorg.com', 
          EmailEncodingKey='UTF-8', LastName='Testing', LanguageLocaleKey='en_US', 
          LocaleSidKey='en_US', TimeZoneSidKey='America/Los_Angeles', UserName='standarsafdewqfewfweFuser@testorg.com');*/
        
        User oppOwner = [SELECT Id,Name,ProfileId FROM User WHERE Name='NA BS User' LIMIT 1]; 
        User u = [SELECT Id,Name,Profile.Name,ProfileId FROM User WHERE Name='David Fabbro' LIMIT 1]; 
       
        User sysAdmin = TestMethodUtilities.getRunningUser();
        update sysAdmin ;
        
        System.runAs(sysAdmin ) {
        /*testUser  = TestMethodUtilities.getRunningUser();
        testUser.ProfileId=p.Id;
        update testUser;*/
                 
        Account a = new Account(Name='a',BillingCountry='IE');
        insert a;
        o1 = new Opportunity(Name='o1',CloseDate=System.Today(),AccountId=a.Id,OwnerId=oppOwner.Id,StageName='Engaged',Product_Target__c='Advanced');
        o2 = new Opportunity(Name='o2',CloseDate=System.Today(),AccountId=a.Id,OwnerId=oppOwner.Id,StageName='Engaged',Product_Target__c='Advanced');
        insert o1;
        insert o2;
      }
      
      
        System.runAs(u) {
        System.debug(o1.OwnerId);
        System.debug(oppOwner.Id);
        System.debug('#################### O1 ID: ' + o1.Id);
        String finalMessage = CloseDuplicateOpportunities.closeDuplicateOpportunities(o1.Id);
        System.assertEquals(finalMessage, '1 similar opportunities have been closed in addition to this one' );
      }
        
        
    
     }

}

 

Debug Log:

 

07:31:21.777 (18777718000)|USER_DEBUG|[42]|DEBUG|#####################CONTEXTOPP ID: 006S00000070NNuIAM
07:31:21.777 (18777726000)|SYSTEM_METHOD_EXIT|[42]|System.debug(ANY)
07:31:21.778 (18778087000)|SOQL_EXECUTE_BEGIN|[44]|Aggregations:0|select Id, AccountId, Owner.Name from Opportunity where Id = :tmpVar1
07:31:21.970 (18970619000)|SOQL_EXECUTE_END|[44]|Rows:0
07:31:21.972 (18972605000)|SYSTEM_METHOD_ENTRY|[46]|System.QueryException.getMessage()
07:31:21.972 (18972697000)|SYSTEM_METHOD_EXIT|[46]|System.QueryException.getMessage()
07:31:21.972 (18972723000)|SYSTEM_METHOD_ENTRY|[46]|System.debug(ANY)
07:31:21.972 (18972741000)|USER_DEBUG|[46]|DEBUG|The following exception has occurred while trying to get the context opp: List has no rows for assignment to SObject
07:31:21.972 (18972750000)|SYSTEM_METHOD_EXIT|[46]|System.debug(ANY)
07:31:21.972 (18972788000)|SYSTEM_METHOD_ENTRY|[49]|System.debug(ANY)
07:31:21.972 (18972819000)|USER_DEBUG|[49]|DEBUG|#####################USERPROFILE NAME: NA Telesales Manager
07:31:21.972 (18972829000)|SYSTEM_METHOD_EXIT|[49]|System.debug(ANY)
07:31:21.972 (18972874000)|EXCEPTION_THROWN|[50]|System.NullPointerException: Attempt to de-reference a null object
07:31:21.972 (18972955000)|METHOD_EXIT|[64]|01pS0000000EZwQ|CloseDuplicateOpportunities.closeDuplicateOpportunities(Id)
07:31:21.972 (18972969000)|POP_TRACE_FLAGS|[64]|01pS0000000EZwQ|CloseDuplicateOpportunities|
07:31:21.983 (18983102000)|FATAL_ERROR|System.NullPointerException: Attempt to de-reference a null object

Class.CloseDuplicateOpportunities.closeDuplicateOpportunities: line 50, column 1
Class.CloseDuplicateOpportunitiesTest.test1: line 64, column 1
07:31:21.983 (18983131000)|FATAL_ERROR|System.NullPointerException: Attempt to de-reference a null object

 

 

 

 

 

 

Best Answer chosen by Admin (Salesforce Developers) 
GlynAGlynA

You're running the test as a user 'David Fabbro', but the Opportunity owner is the user 'NA BS User'.  Does David Fabbro have permissions sufficient to see Opportunity records owned by NA BS User?  If not, the query will not return those records.  Perhaps you could try declaring the CloseDuplicateOpportunities class as "global without sharing", and see if that makes a difference.

 

If this helps, please mark it as a solution, and give kudos (click on the star) if you think I deserve them. Thanks!

 

-Glyn Anderson
Certified Salesforce Developer | Certified Salesforce Administrator

All Answers

Satyendra RawatSatyendra Rawat

Hi,

 

Delete the below line.

 

 System.debug ('#####################CONTEXT OPP OWNER NAME: ' + contextOpp.Owner.Name);
GlynAGlynA

You're running the test as a user 'David Fabbro', but the Opportunity owner is the user 'NA BS User'.  Does David Fabbro have permissions sufficient to see Opportunity records owned by NA BS User?  If not, the query will not return those records.  Perhaps you could try declaring the CloseDuplicateOpportunities class as "global without sharing", and see if that makes a difference.

 

If this helps, please mark it as a solution, and give kudos (click on the star) if you think I deserve them. Thanks!

 

-Glyn Anderson
Certified Salesforce Developer | Certified Salesforce Administrator

This was selected as the best answer
wt35wt35

@Glyn

 

Thanks, I had already found it out a few minutes ago but you were right.

There was no sharing between these two users.

I added "without sharing" to the class and the test passed.

 

Not sure if you can help me further, but I would like to keep my class as with sharing, so I added  the necessary sharing rule but it does not pass. Any ideas? Do you thin I should recalcuate the rules?

 

Thanks

Vinita_SFDCVinita_SFDC

Hello,

You are not creating test data and querying on existing data, for making this work try adding attribute seeAllDate attribute to your test class as follows:

@isTest(seeAllData=True)

 

OR

 

Create test data and then query.

GlynAGlynA

@wt35,

 

Try logging in as NA BS User and creating an Opportunity (make sure NA BS User is the owner).  Then log in as David Fabbro and see if you have access to the Opportunity record.  Tweak permissions until you do.

 

If this is the case (David Fabbro can see Opportunity records of NA BS User in the Salesforce UI), and yet your test still fails, let me know.

 

-Glyn

wt35wt35

No worries Glyn, I think I did something wrong in my sharing rule...now it works.

Thanks for everything