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
KSKumaarKSKumaar 

Test class is not covered completely. Giving exception: NullPointerException

I wrote a Rest api class and it is given below.
 
@RestResource(urlMapping='/threeobjects/*')
Global class MyRest_ThreeObjects_Getting {

    @HttpGet
    global static List<MultiWrapper> doGet(){
        List<MultiWrapper> listmw = new List<MultiWrapper>();
        RestRequest req = RestContext.request;
        RestResponse res = RestContext.response;
        Map<Id, User> contactToUser = new Map<Id, User>();
        for (User u : [select Id, FirstName, LastName, UserName, Email,ContactId from User where ContactId != null limit 1] ) {
            contactToUser.put(u.ContactId, u);
        }
        for (Contact c : [select Id, AccountId, Lastname, Firstname, Email, Account.Id, Account.Name, Account.Phone from Contact where Id in :contactToUser.keySet()]) {
            listmw.add(new MultiWrapper(contactToUser.get(c.Id), c.Account, c));
        }
        return listmw;
    }
    Global class MultiWrapper {
       User us;
       Account acc;
       Contact con;
       Public MultiWrapper (User us, Account acc, Contact con){
           this.us = us;
           this.acc = acc;
           this.con = con;
       }
    }
    @HttpPut
    global static String doPut(){
        List<MultiWrapper> result = doGet();
        String jsonstring = json.serialize(result);
        User us;
        Account acc;
        Contact con;
        list<MultiWrapper> MultiWrapperList = (list<MultiWrapper>)JSON.deserialize(jsonstring,list<MultiWrapper>.class);
        for(MultiWrapper mm : MultiWrapperList){
           us = mm.us;
           acc = mm.acc;
           con = mm.con;
        }
        System.debug('Before queryl:::'+us);
        us = [select Alias from User where id=:us.Id];
        us.Alias = 'Exam';
        update us; 
        System.debug('After query:::'+us);
        return 'User successfully updated';
    }
}

And i wrote test class above class and this test class is covering for get method and giving exception in put method i.e,
System.NullPointerException: Attempt to de-reference a null object

Test class:
 
@IsTest
Private class Test_ThreeObjects_Getting {
    static testMethod void testDoGet() {
        RestRequest req = new RestRequest(); 
        RestResponse res = new RestResponse();
        Account acc = new Account(Name='aa');
        insert acc;
        Contact con = new Contact(LastName='con aa', AccountId=acc.id);
        insert con;
        User u = new User(Lastname = 'Test Name',Alias='some',Email='some@soem.com',
Username='some@some.in',CommunityNickname='some',ProfileId='00e28000000OBjS',
                          ContactID = con.ID,TimeZoneSidKey='America/New_York',LocaleSidKey='en_US',
                          EmailEncodingKey='ISO-8859-1',LanguageLocaleKey='en_US');
        insert u;

        req.requestURI='/services/apexrest/threeobjects';
        req.httpMethod = 'GET';
        RestContext.request = req;
        RestContext.response = res;

        MyRest_ThreeObjects_Getting.MultiWrapper  mulWrap = new MyRest_ThreeObjects_Getting.MultiWrapper(u,acc,con);
        List<MyRest_ThreeObjects_Getting.MultiWrapper> results = MyRest_ThreeObjects_Getting.doGet();
    }
    static testMethod void testDoPut() {

        RestRequest req = new RestRequest(); 
        RestResponse res = new RestResponse();

        req.requestURI='/services/apexrest/threeobjects';
        req.httpMethod = 'PUT';
        RestContext.request = req;
        RestContext.response = res;
        User us = [select Alias from User where id='00528000004fOcq'];
        us.Alias = 'some';
        update us;
        String results1 = MyRest_ThreeObjects_Getting.doPut(); //Giving error here
        System.assertEquals(results1,'User successfully updated');
    }
}
Could anyone please tell me why i am facing this exception and please help me to solve this.

Thanking you
 
Best Answer chosen by KSKumaar
K S LK S L

HI KS,

Modify your Put method as follows. It does not handling the any erros if it comes. and i modify the put method with bulkfication.

@HttpPut
    global static String doPut(){
        String putResult;
        try {
            List<MultiWrapper> result = doGet();
            String jsonstring = json.serialize(result);
            User usa = new User();
            Account acc;
            Contact con;
            Map<Id, User> idToUser = new Map<Id, User>();
            list<MultiWrapper> MultiWrapperList = (list<MultiWrapper>)JSON.deserialize(jsonstring,list<MultiWrapper>.class);
            for(MultiWrapper mm : MultiWrapperList){
               usa = mm.us;
               idToUser.put(usa.Id, usa);               
               acc = mm.acc;
               con = mm.con;
            }
            System.debug('Ids:::'+idToUser.size());
            System.debug('Before queryl:::'+usa);
            
            List<User> main = new List<User>();
            List<User> usa1 = [select Alias from User where id=: idToUser.values()];
            System.debug('usa1:::'+usa1);
            System.debug('usa1 size:::'+usa1.size());
            if(usa1.size() > 0) {
                for(User aa : usa1) {
                    aa.Alias = 'Exam';
                    main.add(aa);
                    update main; 
                }
                putResult = 'User successfully updated';
            }
            else { putResult = 'User not updated or User not found'; }
            System.debug('After query:::'+usa);
            
        }catch(Exception ee) {
            System.debug('The following exception has occurred: ' + ee.getMessage());
        }
        return putResult;
   }
and the test method for above method is as follows.
 
Account acc = new Account(Name='aa');
        insert acc;
        Contact con = new Contact(LastName='con aa', AccountId=acc.id);
        insert con;
        User u = new User(Lastname = 'Test Name',Alias='some1',Email='some1@soem.com',
                          Username='some1@some.in',CommunityNickname='some',ProfileId='00e28000000OBjB',
                          ContactID = con.ID,TimeZoneSidKey='America/New_York',LocaleSidKey='en_US',
                          EmailEncodingKey='ISO-8859-1',LanguageLocaleKey='en_US');
        insert u; 
        
        RestRequest req = new RestRequest(); 
        RestResponse res = new RestResponse();  
        
        req.requestURI='/services/apexrest/threeobjects';
        req.httpMethod = 'PUT';
        RestContext.request = req;
        RestContext.response = res;
        List<User> main = new List<User>();
        List<User> usa1 = [select Alias from User where id= '00528000004fOcq'];
        if(usa1.size() > 0) {
           User thisUser = [SELECT Id FROM User WHERE Id = :UserInfo.getUserId()];
            System.runAs(thisUser) { 
             for(User aa : usa1) {
                  aa.Alias = 'Exam';
                  main.add(aa);
                  update main;
             }
             String results1 = MyRest_ThreeObjects_Getting.doPut();
             System.debug('results1:::'+results1);
             System.assertEquals(results1,'User successfully updated');
            }
             
        }
        else {
            String results1 = MyRest_ThreeObjects_Getting.doPut();
            System.debug('results1:::'+results1);
            System.assertEquals(results1,'User not updated or User not found'); 
        }


check with these answers and let me know

Thank you.

All Answers

Waqar Hussain SFWaqar Hussain SF
On which line are you getting this error message?
KSKumaarKSKumaar

Hi

@NABEEL KT
 

In rest class, error is comng at line number 42 and in test class error is coming at line number 36

Please see test class, i already mentined that 

Waqar Hussain SFWaqar Hussain SF
@RestResource(urlMapping='/threeobjects/*')
Global class MyRest_ThreeObjects_Getting {

    @HttpGet
    global static List<MultiWrapper> doGet(){
        List<MultiWrapper> listmw = new List<MultiWrapper>();
        RestRequest req = RestContext.request;
        RestResponse res = RestContext.response;
        Map<Id, User> contactToUser = new Map<Id, User>();
        for (User u : [select Id, FirstName, LastName, UserName, Email,ContactId from User where ContactId != null limit 1] ) {
            contactToUser.put(u.ContactId, u);
        }
        for (Contact c : [select Id, AccountId, Lastname, Firstname, Email, Account.Id, Account.Name, Account.Phone from Contact where Id in :contactToUser.keySet()]) {
            listmw.add(new MultiWrapper(contactToUser.get(c.Id), c.Account, c));
        }
        return listmw;
    }
    Global class MultiWrapper {
       User us;
       Account acc;
       Contact con;
       Public MultiWrapper (User us, Account acc, Contact con){
           this.us = us;
           this.acc = acc;
           this.con = con;
       }
    }
    @HttpPut
    global static String doPut(){
        List<MultiWrapper> result = doGet();
        String jsonstring = json.serialize(result);
        User us;
        Account acc;
        Contact con;
        list<MultiWrapper> MultiWrapperList = (list<MultiWrapper>)JSON.deserialize(jsonstring,list<MultiWrapper>.class);
        for(MultiWrapper mm : MultiWrapperList){
           us = mm.us;
           acc = mm.acc;
           con = mm.con;
        }
        System.debug('Before queryl:::'+us);
if(us!=null && us.Id !=null){
        us = [select Alias from User where id=:us.Id];
        us.Alias = 'Exam';
        update us; 
        System.debug('After query:::'+us);
        return 'User successfully updated';
}else{
return 'User not found';
}
    }
}

try above code
Leo10Leo10
Hi 
Try this test class also
@IsTest
Private class Test_ThreeObjects_Getting {
    static testMethod void testDoGetDoPut() {
        RestRequest req = new RestRequest(); 
        RestResponse res = new RestResponse();
        Account acc = new Account(Name='aa');
        insert acc;
        Contact con = new Contact(LastName='con aa', AccountId=acc.id);
        insert con;
        User u = new User(Lastname = 'Test Name',Alias='some',Email='some@soem.com',
                          Username='some@some.in',CommunityNickname='some',ProfileId='00e28000000OBjS',
                          ContactID = con.ID,TimeZoneSidKey='America/New_York',LocaleSidKey='en_US',
                          EmailEncodingKey='ISO-8859-1',LanguageLocaleKey='en_US');
        insert u;
        req.requestURI='/services/apexrest/threeobjects';
        req.httpMethod = 'GET';
        RestContext.request = req;
        RestContext.response = res;
        MyRest_ThreeObjects_Getting.MultiWrapper  mulWrap = new MyRest_ThreeObjects_Getting.MultiWrapper(u,acc,con);
        List<MyRest_ThreeObjects_Getting.MultiWrapper> results = MyRest_ThreeObjects_Getting.doGet();
    
        u.Alias = 'some2';
        update u;
        String results1 = MyRest_ThreeObjects_Getting.doPut();
        System.assertEquals(results1,'User successfully updated');

    }
}

 
KSKumaarKSKumaar
NABEEL KT
I tried with test class which is provided by you. Even though it is giving same exception at same line numbers
 
K S LK S L

HI KS,

Modify your Put method as follows. It does not handling the any erros if it comes. and i modify the put method with bulkfication.

@HttpPut
    global static String doPut(){
        String putResult;
        try {
            List<MultiWrapper> result = doGet();
            String jsonstring = json.serialize(result);
            User usa = new User();
            Account acc;
            Contact con;
            Map<Id, User> idToUser = new Map<Id, User>();
            list<MultiWrapper> MultiWrapperList = (list<MultiWrapper>)JSON.deserialize(jsonstring,list<MultiWrapper>.class);
            for(MultiWrapper mm : MultiWrapperList){
               usa = mm.us;
               idToUser.put(usa.Id, usa);               
               acc = mm.acc;
               con = mm.con;
            }
            System.debug('Ids:::'+idToUser.size());
            System.debug('Before queryl:::'+usa);
            
            List<User> main = new List<User>();
            List<User> usa1 = [select Alias from User where id=: idToUser.values()];
            System.debug('usa1:::'+usa1);
            System.debug('usa1 size:::'+usa1.size());
            if(usa1.size() > 0) {
                for(User aa : usa1) {
                    aa.Alias = 'Exam';
                    main.add(aa);
                    update main; 
                }
                putResult = 'User successfully updated';
            }
            else { putResult = 'User not updated or User not found'; }
            System.debug('After query:::'+usa);
            
        }catch(Exception ee) {
            System.debug('The following exception has occurred: ' + ee.getMessage());
        }
        return putResult;
   }
and the test method for above method is as follows.
 
Account acc = new Account(Name='aa');
        insert acc;
        Contact con = new Contact(LastName='con aa', AccountId=acc.id);
        insert con;
        User u = new User(Lastname = 'Test Name',Alias='some1',Email='some1@soem.com',
                          Username='some1@some.in',CommunityNickname='some',ProfileId='00e28000000OBjB',
                          ContactID = con.ID,TimeZoneSidKey='America/New_York',LocaleSidKey='en_US',
                          EmailEncodingKey='ISO-8859-1',LanguageLocaleKey='en_US');
        insert u; 
        
        RestRequest req = new RestRequest(); 
        RestResponse res = new RestResponse();  
        
        req.requestURI='/services/apexrest/threeobjects';
        req.httpMethod = 'PUT';
        RestContext.request = req;
        RestContext.response = res;
        List<User> main = new List<User>();
        List<User> usa1 = [select Alias from User where id= '00528000004fOcq'];
        if(usa1.size() > 0) {
           User thisUser = [SELECT Id FROM User WHERE Id = :UserInfo.getUserId()];
            System.runAs(thisUser) { 
             for(User aa : usa1) {
                  aa.Alias = 'Exam';
                  main.add(aa);
                  update main;
             }
             String results1 = MyRest_ThreeObjects_Getting.doPut();
             System.debug('results1:::'+results1);
             System.assertEquals(results1,'User successfully updated');
            }
             
        }
        else {
            String results1 = MyRest_ThreeObjects_Getting.doPut();
            System.debug('results1:::'+results1);
            System.assertEquals(results1,'User not updated or User not found'); 
        }


check with these answers and let me know

Thank you.

This was selected as the best answer