+ Start a Discussion
wt35wt35 

Error in Test Class: System.NullPointerException: Attempt to de-reference a null object

 

I get the following error when running my test class: 

Error Message System.NullPointerException: Attempt to de-reference a null object Stack Trace Class.CloseDuplicateOpportunities.closeDuplicateOpportunities: line 22, column 1
Class.CloseDuplicateOpportunitiesTest.test1: line 27, column 1

 

I have come across this error message several times in the past, bu t cannot understand why it happens here.

It looks like the Profile is not retrieved when my method is called by the test class.

I would like to point out that it works perfect when doing tests manually.

 

 

Test Class:

 

@isTest
public class CloseDuplicateOpportunitiesTest {

    @isTest(SeeAllData=true) static void test1() {
    
        //User oppOwner = [SELECT Id FROM User WHERE Name='NA BS User']; 

        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');
        
        
        Account a = new Account(Name='a',BillingCountry='IE');
        insert a;
        Opportunity o1 = new Opportunity(Name='o1',CloseDate=System.Today(),AccountId=a.Id,OwnerId=oppOwner.Id,StageName='Engaged',Product_Target__c='Advanced');
        Opportunity 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) {
        String finalMessage = CloseDuplicateOpportunities.closeDuplicateOpportunities(o1.Id);
        System.assertEquals(finalMessage, '1 similar opportunities have been closed in addition to this one' );
      }
        
        
    }






}

 

 

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()];


        /*********************************************************/
        /*****************AUTHORIZED USER ************************/
        /*********************************************************/
   
        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());
        }
        
        
        if (   (userProfile.Name.equals('NA Telesales Rep') ||
                userProfile.Name.equals('NA Telesales Manager') ||
                userProfile.Name.equals('NA Territory Manager - Outbound')) && 
                contextOpp.Owner.Name == 'NA BS User' )
        {
            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 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.size() > 0)
            {
                for (Opportunity o : oppsToUpdate)
                {
                 o.StageName = 'Closed Lost';
                 o.Reason_For_Closed_Lost__c = 'Close - TS Duplicate';
                }

                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;
    }


}

 

 

Thanks!

Subramani_SFDCSubramani_SFDC

add this line

 

insert u;

 

 

wt35wt35

Thanks @subra but no joy, it's the exact same error message

Satyendra RawatSatyendra Rawat

Hi,

 

I have changes code,

plz update class code.

 

 

 

 

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()];


/*********************************************************/
/*****************AUTHORIZED USER ************************/
/*********************************************************/

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());
}


if ( (userProfile.Name.equals('NA Telesales Rep') ||
userProfile.Name.equals('NA Telesales Manager') ||
userProfile.Name.equals('NA Territory Manager - Outbound')) && (contextOpp.Owner!=null &&
contextOpp.Owner.Name == 'NA BS User') )
{
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 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 = 'Closed Lost';
o.Reason_For_Closed_Lost__c = 'Close - TS Duplicate';
}

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;
}


}

wt35wt35

Thanks but does not change anything....

RockzRockz

Hi..

 

Hope this will help :

 

@isTest
public class CloseDuplicateOpportunitiesTest {

    @isTest(SeeAllData=true) 
	static void test1() {
    
        //User oppOwner = [SELECT Id FROM User WHERE Name='NA BS User']; 

        Profile p = [SELECT Id FROM Profile limit 1]; 
        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');
        
        
        Account a = new Account(Name='a',BillingCountry='IE');
        insert a;
        Opportunity o1 = new Opportunity(Name='o1',CloseDate=System.Today(),AccountId=a.Id,OwnerId=oppOwner.Id,StageName='Engaged',Product_Target__c='Advanced');
        Opportunity 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(Id = :UserInfo.getUserId()) {
         String finalMessage = CloseDuplicateOpportunities.closeDuplicateOpportunities(o1.Id);
        System.assertEquals(finalMessage, '1 similar opportunities have been closed in addition to this one' );
      }    
    }

}

 

Please accept my answer as a solution if my solution was helpful. This will make it available to others as a proper answer. If you felt that I went above and beyond please give me Kudos by clicking on on the star icon.

 

Thanks,

Cool Sfdc

 

wt35wt35

I can see that you have change the runAs to:

 

System.runAs(Id = :UserInfo.getUserId())

 

Sorry but I do not see how it could solve my issue, as I really want my class to run as a specific user and not the logged-in user...