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
Hermann OuréHermann Ouré 

How to write a Test for JSON Generator in a callout?

Hello,

I have written a class for send Slack Notification anytime a Community Post or Answer is made in our client portal. But my test class only cover 54% of my code. I struggle to write a test for the JSON Generator as show on the pic

User-added image
How can I test JSON Generator in my class
Thanks!

here is my code:
 
public class SlackNotificationCommunityPost {
    
    /*
    -------------------------------------------------------------------------------------------------
    -- - Description   : Class to send Slack notification based on QuestionPost created on Community
    -- -----------  ----  -------  ------------------------------------------------------------------
     */
    
    public class slackRequest {
        //Use @InvocableVariable to call Process Builder
        @InvocableVariable(label='title')
        public String title; 
        
        @InvocableVariable(label='id')
        public String id; 
        
        @InvocableVariable(label='name')
        public String name;   
        
        //**H.O: (CODE UPDATE) Answer to Community Post 
        @InvocableVariable(label='type')
        public String type;
    }
    
    @InvocableMethod(label='Publish New Community posts to Slack')
    public static void publishNewCommunityPostsToSlack(List<slackRequest> requests) {

        //String webhookURL='https://hooks.slack.com/services/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';
        String webhookURL = system.label.Param_Slack_Token;
        String msg;
        String channelName;
        
        for(slackRequest r:requests){
            
            //check if the post has and Id, name, title
            if(r.id != null && r.name != null && r.title != null && r.type == 'QuestionPost') {
                System.debug('### SlackNotificationCommunityPosts new post');
                channelName = '#' +Label.Slack_Community_Channel;
                msg = 'A new community post has been created : *'+r.title+'* - By User : (*'+r.name+'*)';
                msg += '\nLink to Community post : '+Network.communitiesLanding().getUrl()+'question/'+r.id;
             
            //**H.O: (Statement Update) Answer to Community Post
            } else if (r.type != 'QuestionPost') {
                System.debug('### SlackNotificationCommunityPosts answers');
                channelName = '#' +Label.Slack_Community_Channel;
                msg = '(*'+r.name+'*) has written an answer to Community post : '+Network.communitiesLanding().getUrl()+'question/'+r.id;
                
            }
            
            //Generate JSON for request
            try {
                if (r.id != null && r.title !=null && r.name != null ) {
                   System.debug('### SlackNotificationCommunityPosts sending message');
                   JSONGenerator gen = JSON.createGenerator(true);
                    gen.writeStartObject(); //Inserts {
                    gen.writeStringField('text', msg);
                    gen.writeStringField('channel', channelName);
                    gen.writeStringField('username', 'bot-support');
                    gen.writeStringField('icon_emoji', ':smartplus:');
                    gen.writeEndObject(); //Inserts }
                    String body = gen.getAsString(); //Translates JSONGenerator to string to be passed to callout
                    System.debug('### SlackNotificationCommunityPosts body: '+ body);
                    System.enqueueJob(new qCallOut(webhookURL, 'POST', body)); // Send request
      
               	 } else {
                    System.debug('### SlackNotificationCommunityPosts Id = '+ r.id);
                    return; 
                }
                
            }
            catch (exception e) {
                System.debug('### SlackNotificationCommunityPosts error:' +e);
            }
            
        }
     
    }
    
     public class qCallOut implements System.Queueable, Database.AllowsCallouts {
         
        private final String url;
        private final String method;
        private final String body;
         
        public qCallOut(String url, String method, String body) {
            this.url = url;
            this.method = method;
            this.body = body;
        }
         
        public void execute(System.QueueableContext ctx) {
            HttpRequest req = new HttpRequest();
            req.setEndpoint(url);
            req.setMethod(method);
            req.setBody(body);
            Http http = new Http();
            // to pass when process builder is invoked by another test class
            if(!Test.isRunningTest()){  
              HttpResponse res = http.send(req);
            }
        }
         
     }

}

here is my test class:
 
@isTest (seeAllData=true)
public class SlackNotificationCommunityPostTest {
    
    static testMethod void testPublishNewCommunityPostsToSlack() {
        Test.setMock(HttpCalloutMock.class, new mockCallout());
        List<SlackNotificationCommunityPost.slackRequest> requests = new List<SlackNotificationCommunityPost.slackRequest>();
        SlackNotificationCommunityPost.slackRequest r = new SlackNotificationCommunityPost.slackRequest();
        r.id= 'Test';
        r.name= 'Test';
        r.title= 'Test';
        r.type= 'Test';
        requests.add(r);
        SlackNotificationCommunityPost.publishNewCommunityPostsToSlack(requests);
        System.debug('check Post id: '+r.id);
    }
  
    static testmethod void testQueueable() {
        String url = 'https://hooks.slackTest.com';
        String method = 'Post';
        String body = 'body';
        
        SlackNotificationCommunityPost.qCallOut qCalloutTest = new SlackNotificationCommunityPost.qCallOut(url, method, body);
        Test.startTest();
        System.enqueueJob(qCalloutTest);
        Test.stopTest();
    }
    
    public class mockCallout implements HttpCalloutMock {
        public HttpResponse respond(HttpRequest request) {
            
            //Create a fake response
            HttpResponse res = new HttpResponse();
            res.setBody( '{"text":"value"}');
            res.setStatusCode(200);
            return res;
        }
    }

}

 
Hermann OuréHermann Ouré

ps: I forgot to mention that the log shows the following error:
System.NullPointerException: Attempt to de-reference a null object

Class.SlackNotificationCommunityPost.publishNewCommunityPostsToSlack: line 46
line 46 is this:
User-added image

dhw ckslddhw cksld
Can you share the complete program list? I need help to integrate it with my post. You can learn more (https://generatorsadvisor.com/best-inverter-generators-for-camping/) about it.