You need to sign in to do that
Don't have an account?

test class showing null pointer exception
Hi All,
my test class is as below:-
@istest
private class ContentDocumentLinkTriggerHelperTest {
@isTest
static void ContentDocumentLinkTriggerHelperTestMethod()
{
Account acc = new Account(name='test acc');
insert acc;
Contact con = new Contact(lastname='test cont',accountid=acc.id);
insert con;
Opportunity opp = new Opportunity(name='testoppty',AccountId=acc.id,stageName='Qualification',closedate=system.today());
insert opp;
ContentVersion content=new ContentVersion();
content.Title='Header_Picture1';
content.PathOnClient='/' + content.Title + '.jpg';
Blob bodyBlob=Blob.valueOf('Unit Test ContentVersion Body');
content.VersionData=bodyBlob;
//content.LinkedEntityId=sub.id;
content.origin = 'H';
insert content;
ContentVersion testContent = [SELECT id, ContentDocumentId FROM ContentVersion where Id = :content.Id];
List<ContentDocument> documents = [SELECT Id, Title, LatestPublishedVersionId FROM ContentDocument LIMIT 1];
System.assertEquals(documents.size(), 1);
System.assertEquals(documents[0].LatestPublishedVersionId, content.Id);
System.assertEquals(documents[0].Title, content.Title);
ContentDocumentLink contentlink=new ContentDocumentLink();
contentlink.LinkedEntityId=acc.id;
contentlink.contentdocumentid=testContent.ContentDocumentId;
contentlink.ShareType = 'V';
insert contentlink;
SocialPost sp = new SocialPost(Name= 'image');
insert sp;
String tags = 'test tags';
Map<String,id> predictionTags = new Map<String, id>();
List<ApiLog__c> apiLogsList = new List<ApiLog__c>();
set<id> SocialPostIds = new Set<id>();
SocialPostIds.add(sp.Id);
Predictions__c pc = new Predictions__c();
pc.Social_Post__c = sp.id;
insert pc;
ApiLog__c al = new ApiLog__c();
insert al;
ContentDocumentLinkTriggerHelper.getPredictions(SocialPostIds);
ContentDocumentLinkTriggerHelper.getAccessToken(sp);
ContentDocumentLinkTriggerHelper.addTagsToSocialPost(sp, tags, apiLogsList) ;
ContentDocumentLinkTriggerHelper.getPredictionsFuture(SocialPostIds);
ContentDocumentLinkTriggerHelper.parseImageResponse();
test.starttest();
insert contentlink;
ContentDocumentLinkTriggerHelper.getPredictionsFuture(SocialPostIds);
test.stopTest();
}
@istest
static void AddTagsToPostTest(){
SocialPost sp = new SocialPost(Name= 'image');
insert sp;
String tags = 'test tags';
ApiLog__c al = new ApiLog__c();
al.SocialPost__c = sp.id;
List<ApiLog__c> apiLogsList = new List<ApiLog__c>();
apiLogsList.add(al);
set<id> SocialPostIds = new Set<id>();
SocialPostIds.add(sp.Id);
test.startTest();
insert apiLogsList;
ContentDocumentLinkTriggerHelper.getAccessToken(sp);
ContentDocumentLinkTriggerHelper.addTagsToSocialPost(sp, tags, apiLogsList) ;
ContentDocumentLinkTriggerHelper.getPredictionsFuture(SocialPostIds);
test.stopTest();
}
@isTest
static void testAccessTokenCallout() {
// Set mock callout class
Test.setMock(HttpCalloutMock.class, new MockHttpResponseGenerator());
// First request
Http h = new Http();
HttpRequest req1 = new HttpRequest();
req1.setEndpoint('http://mygreatservice.com/foo/bar');
req1.setMethod('POST');
req1.setBody('Access Token');
HttpResponse res1 = h.send(req1);
System.assertEquals('{"access_token":"somevalidAccessToken"}', res1.getBody());
// Second request
HttpRequest req2 = new HttpRequest();
req2.setEndpoint('http://mygreatservice.com/foo/bar');
req2.setMethod('POST');
req2.setBody('tagsToSend');
HttpResponse res2 = h.send(req2);
System.assertEquals('{"tagsToSend" : "12345"}', res2.getBody());
SocialPost sp = new SocialPost(Name= 'image');
insert sp;
set<id> SocialPostIds = new Set<id>();
SocialPostIds.add(sp.Id);
}
}
its showing me this error:-System.NullPointerException: Attempt to de-reference a null object At bold lines
Can Anyone help me with this?/
guide me?
my test class is as below:-
@istest
private class ContentDocumentLinkTriggerHelperTest {
@isTest
static void ContentDocumentLinkTriggerHelperTestMethod()
{
Account acc = new Account(name='test acc');
insert acc;
Contact con = new Contact(lastname='test cont',accountid=acc.id);
insert con;
Opportunity opp = new Opportunity(name='testoppty',AccountId=acc.id,stageName='Qualification',closedate=system.today());
insert opp;
ContentVersion content=new ContentVersion();
content.Title='Header_Picture1';
content.PathOnClient='/' + content.Title + '.jpg';
Blob bodyBlob=Blob.valueOf('Unit Test ContentVersion Body');
content.VersionData=bodyBlob;
//content.LinkedEntityId=sub.id;
content.origin = 'H';
insert content;
ContentVersion testContent = [SELECT id, ContentDocumentId FROM ContentVersion where Id = :content.Id];
List<ContentDocument> documents = [SELECT Id, Title, LatestPublishedVersionId FROM ContentDocument LIMIT 1];
System.assertEquals(documents.size(), 1);
System.assertEquals(documents[0].LatestPublishedVersionId, content.Id);
System.assertEquals(documents[0].Title, content.Title);
ContentDocumentLink contentlink=new ContentDocumentLink();
contentlink.LinkedEntityId=acc.id;
contentlink.contentdocumentid=testContent.ContentDocumentId;
contentlink.ShareType = 'V';
insert contentlink;
SocialPost sp = new SocialPost(Name= 'image');
insert sp;
String tags = 'test tags';
Map<String,id> predictionTags = new Map<String, id>();
List<ApiLog__c> apiLogsList = new List<ApiLog__c>();
set<id> SocialPostIds = new Set<id>();
SocialPostIds.add(sp.Id);
Predictions__c pc = new Predictions__c();
pc.Social_Post__c = sp.id;
insert pc;
ApiLog__c al = new ApiLog__c();
insert al;
ContentDocumentLinkTriggerHelper.getPredictions(SocialPostIds);
ContentDocumentLinkTriggerHelper.getAccessToken(sp);
ContentDocumentLinkTriggerHelper.addTagsToSocialPost(sp, tags, apiLogsList) ;
ContentDocumentLinkTriggerHelper.getPredictionsFuture(SocialPostIds);
ContentDocumentLinkTriggerHelper.parseImageResponse();
test.starttest();
insert contentlink;
ContentDocumentLinkTriggerHelper.getPredictionsFuture(SocialPostIds);
test.stopTest();
}
@istest
static void AddTagsToPostTest(){
SocialPost sp = new SocialPost(Name= 'image');
insert sp;
String tags = 'test tags';
ApiLog__c al = new ApiLog__c();
al.SocialPost__c = sp.id;
List<ApiLog__c> apiLogsList = new List<ApiLog__c>();
apiLogsList.add(al);
set<id> SocialPostIds = new Set<id>();
SocialPostIds.add(sp.Id);
test.startTest();
insert apiLogsList;
ContentDocumentLinkTriggerHelper.getAccessToken(sp);
ContentDocumentLinkTriggerHelper.addTagsToSocialPost(sp, tags, apiLogsList) ;
ContentDocumentLinkTriggerHelper.getPredictionsFuture(SocialPostIds);
test.stopTest();
}
@isTest
static void testAccessTokenCallout() {
// Set mock callout class
Test.setMock(HttpCalloutMock.class, new MockHttpResponseGenerator());
// First request
Http h = new Http();
HttpRequest req1 = new HttpRequest();
req1.setEndpoint('http://mygreatservice.com/foo/bar');
req1.setMethod('POST');
req1.setBody('Access Token');
HttpResponse res1 = h.send(req1);
System.assertEquals('{"access_token":"somevalidAccessToken"}', res1.getBody());
// Second request
HttpRequest req2 = new HttpRequest();
req2.setEndpoint('http://mygreatservice.com/foo/bar');
req2.setMethod('POST');
req2.setBody('tagsToSend');
HttpResponse res2 = h.send(req2);
System.assertEquals('{"tagsToSend" : "12345"}', res2.getBody());
SocialPost sp = new SocialPost(Name= 'image');
insert sp;
set<id> SocialPostIds = new Set<id>();
SocialPostIds.add(sp.Id);
}
}
its showing me this error:-System.NullPointerException: Attempt to de-reference a null object At bold lines
Can Anyone help me with this?/
guide me?
Can you specify the line number on which the exception is happening by checking the debug logs?
ContentDocumentLinkTriggerHelper
my Helper is given below:-
/*
* Trigger Helper Class to parse image response
* Parse Image response From social post
* */
public without sharing class ContentDocumentLinkTriggerHelper {
public static List<ContentDocumentLink> newList;
public static List<ContentDocumentLink> oldList;
public static Map<Id, ContentDocumentLink> newMap;
public static Map<Id, ContentDocumentLink> oldMap;
public static Boolean runTrigger = true;
// method to Parse Image response from social Post
public static void parseImageResponse(){
List<Predictions__c> pdcList = new List<Predictions__c>();
Set<Id> setSocialPostIds = new Set<Id>();
for(contentdocumentlink cdl : newList){
if( cdl.LinkedEntityId != null
&& String.valueOf((cdl.LinkedEntityId)).startsWith('0ST')
&& ( !setSocialPostIds.contains( cdl.LinkedEntityId ))) {
setSocialPostIds.add( cdl.LinkedEntityId );
}
}
//Check Prediction list Has value or not
if( setSocialPostIds.size() > 0 ){
getPredictionsFuture( setSocialPostIds );
}
}
public static void getPredictions( Set<Id> setSocialPostIds ) {
Map<Id, SocialPost> mapSocialPost = new Map<Id, SocialPost>( [ Select Id, ExternalPostId,
R6PostId,
AttachmentType
From SocialPost
Where Id in: setSocialPostIds
] );
// get all images for social post
List<contentdocumentlink> cdlList = new List<contentdocumentlink>([Select id,
contentdocumentId,
LinkedEntityId
from contentdocumentlink
where LinkedEntityId IN: setSocialPostIds]);
Map<Id, Id> contentDocumentIdToSPIds = new Map<Id, Id>();
// key = image URL and value Social Post ID
Map<String, Id> imageUrlMap = new Map<String, Id>();
if(cdlList.size() > 0){
for(contentdocumentlink cdl : cdlList){
//if(mapSocialPost.get(cdl.LinkedEntityId).AttachmentType == 'IMAGE'){
contentDocumentIdToSPIds.put(cdl.contentdocumentId, cdl.LinkedEntityId);
//}
}
}
if(contentDocumentIdToSPIds.size() > 0){
List<ContentVersion> contentVersionList = new List<ContentVersion>([Select id,
VersionData,
ContentUrl,
contentdocumentId
from ContentVersion
where contentdocumentId IN: contentDocumentIdToSPIds.keyset()]);
if(contentVersionList.size() > 0){
for(ContentVersion cv: contentVersionList){
/*if( cv.ContentURL == null ) {
imageUrlMap.put('http://pbs.twimg.com/media/DolEbpoW0AASeBS.jpg' , contentDocumentIdToSPIds.get( cv.contentdocumentId ));
}
else {
imageUrlMap.put(cv.ContentUrl , contentDocumentIdToSPIds.get( cv.contentdocumentId ));
}*/
imageUrlMap.put(cv.ContentUrl , contentDocumentIdToSPIds.get( cv.contentdocumentId ));
}
}
}
List<Predictions__c> predictions = new List<Predictions__c>();
List<Predictions__c> tagPredictions = new List<Predictions__c>();
List<Predictions__c> noTagPredictions = new List<Predictions__c>();
Map<Id, List<Predictions__c>> mapSocialPostIdToPredictionsForTag = new Map<Id, List<Predictions__c>>();
List<ApiLog__c> apiLogsList = new List<ApiLog__c>();
// loop over images
if(imageUrlMap.size() > 0){
for(String imageURL : imageUrlMap.keyset()){
// get predictions using below method
EinsteinVision_PredictionService ep = new EinsteinVision_PredictionService();
//ep.predictUrl('OXTA2COBQGR3FKJ5XGEZ4QJALI','https://scontent-maa2-1.xx.fbcdn.net/v/t1.0-9/15056354_1361890883844444_8397543633573087634_n.jpg?_nc_cat=108&oh=2cb4f2d79fd056158e571d1519da55ca&oe=5C1E938F',''));
EinsteinVision_PredictionResult predictRes;
try {
predictRes = ep.predictUrl('OXTA2COBQGR3FKJ5XGEZ4QJALI', imageURL,'');
}
catch(Exception e ) {
// create log
ApiLog__c apiLog = new ApiLog__c();
apiLog.EndPoint__c = '';
apiLog.ImageURL__c = imageURL;
apiLog.Prediction__c = '';
apiLog.RequestBody__c = 'OXTA2COBQGR3FKJ5XGEZ4QJALI'+' , '+ imageURL + '';
apiLog.ResponseBody__c = ''+predictRes;
apiLog.SocialPost__c = imageUrlMap.get(imageURL);
apiLog.StatusCode__c = '';
apiLog.Type__c = 'ev';
apiLogsList.add(apiLog);
}
if( predictRes != null && predictRes.probabilities != null ) {
List<EinsteinVision_Probability> einProbabilities = predictRes.probabilities;
if( einProbabilities.size() > 0 ) {
Predictions__c pc = new Predictions__c();
pc.Image_URL__c = imageURL;
pc.Social_Post__c = imageUrlMap.get(imageURL);
pc.Response_Body__c = String.valueOf( predictRes );
pc.Model_Id__c = 'OXTA2COBQGR3FKJ5XGEZ4QJALI';
// Parse resposne and create prediction object data
for( EinsteinVision_Probability ein : einProbabilities ) {
if( ein.probability != null ) {
Double probability = Double.valueOf( ein.probability );
if( (probability * 100) >= 99 ) {
pc.Label__c = pc.Label__c == null ? ein.label : pc.Label__c + ',' + ein.label;
pc.Probability__c = probability;
}
}
}
// take it from custom label
if( pc.Label__c != null ) {
tagPredictions.add( pc );
}
else {
noTagPredictions.add(pc);
}
List<Predictions__c> spPredictions = mapSocialPostIdToPredictionsForTag.containsKey( pc.Social_Post__c ) ? mapSocialPostIdToPredictionsForTag.get( pc.Social_Post__c ) : new List<Predictions__c>();
spPredictions.add( pc );
mapSocialPostIdToPredictionsForTag.put( pc.Social_Post__c, spPredictions );
}
}
}
}
predictions.addAll( tagPredictions );
predictions.addAll( noTagPredictions );
if( predictions.size() > 0 ) {
for( Id socialPostId : mapSocialPostIdToPredictionsForTag.keySet() ) {
String tags = '';
Map<String , Id > predictionTags= new Map<String , Id>();
Set<String> setExitingTags = new Set<String>();
for( Predictions__c prediction : mapSocialPostIdToPredictionsForTag.get( socialPostId )) {
if( prediction.Label__c != null ) {
for( String tag : prediction.Label__c.split( ',' )) {
if( setExitingTags.add( tag )) {
tags += ( tags == '' ) ? prediction.Label__c : ',' + prediction.Label__c;
}
}
}
predictionTags.put( tags , prediction.Id );
}
if( tags != '' && tags.length() > 0 ) {
SocialPost socialPostObj = mapSocialPost.get( socialPostId );
// make an API call to social studio to add tags
addTagsToSocialPost( socialPostObj, tags ,
//predictionTags,
apiLogsList);
// create log
}
}
insert predictions;
}
}
@future(callout = True)
public static void getPredictionsFuture( Set<Id> setSocialPostIds ) {
getPredictions( setSocialPostIds );
}
public static void addTagsToSocialPost( SocialPost spObj,
String tags ,
//Map<String, Id> predictionTags,
List<ApiLog__c> apiLogsList){
// Api call to update tag to post
List<ApiLog__c> apiLogList = new List<ApiLog__c>();
apiLogList.addAll(apiLogsList);
Map<String, List<ApiLog__c>> accessTokenMap = getAccessToken( spObj
//, tags , predictionTags
);
String accessToken = '';
for(String at : accessTokenMap.keySet()){
accessToken = at;
}
apiLogList.addAll(accessTokenMap.get(accessToken));
HttpRequest req = new HttpRequest();
req.setMethod('POST');
req.setEndpoint( 'https://api.radian6.com/socialcloud/v1/post/workflow/tags/' + spObj.R6PostId);
req.setHeader('auth_token', accessToken);
req.setHeader('auth_appkey', Label.AppKey);
Http binding = new Http();
String tagsToSend = 'tags:'+ tags;
req.setBody('tags='+tags);
req.setHeader('content-type','application/x-www-form-urlencoded');
HttpResponse res;
res = binding.send( req );
try{
res = binding.send( req );
ApiLog__c apiLog = new ApiLog__c();
apiLog.EndPoint__c = req.getEndpoint();
apiLog.ImageURL__c = '';
//apiLog.Prediction__c = predictionTags.get(tags);
apiLog.RequestBody__c = req.getBody();
apiLog.ResponseBody__c = res.getBody();
apiLog.SocialPost__c = spObj.Id;
apiLog.StatusCode__c = String.valueOf(res.getStatusCode());
apiLog.Type__c = 'Social Studio';
apiLogList.add(apiLog);
}catch(Exception e){
ApiLog__c apiLog = new ApiLog__c();
apiLog.EndPoint__c = req.getEndpoint();
apiLog.ImageURL__c = '';
//apiLog.Prediction__c = predictionTags.get(tags);
apiLog.RequestBody__c = req.getBody();
apiLog.ResponseBody__c = res.getBody();
apiLog.SocialPost__c = spObj.Id;
apiLog.StatusCode__c = String.valueOf(res.getStatusCode());
apiLog.Type__c = 'Social Studio';
apiLogList.add(apiLog);
}
insert apiLogList;
}
public static Map<String, List<ApiLog__c>> getAccessToken(SocialPost spObj){
// Api call to update tag to post
Map<String, List<ApiLog__c>> accessTokenWithApiLog = new Map<String, List<ApiLog__c>>();
List<ApiLog__c> apiLogsList = new List<ApiLog__c>();
HttpRequest req = new HttpRequest();
req.setMethod('GET');
req.setEndpoint( 'https://api.radian6.com/socialcloud/v1/auth/authenticate/' );
req.setHeader('auth_user', 'shashikant.idealyst');
req.setHeader('auth_pass', 'SFDCdev@123456789');
req.setHeader('auth_appkey', Label.AppKey);
Http binding = new Http();
HttpResponse res;
String accessToken = '';
try{
res = binding.send( req );
if(res.getStatusCode() == 200){
String resBody = res.getBody();
if(resBody.contains('token')){
accessToken = resBody.substringBetween('<token>' , '</token>');
}
}
ApiLog__c apiLog = new ApiLog__c();
apiLog.EndPoint__c = req.getEndpoint();
apiLog.ImageURL__c = '';
//apiLog.Prediction__c = predictionTags.get(tags);
apiLog.RequestBody__c = req.getBody();
apiLog.ResponseBody__c = res.getBody();
apiLog.SocialPost__c = spObj.Id;
apiLog.StatusCode__c = String.valueOf(res.getStatusCode());
apiLog.Type__c = 'Social Studio';
apiLogsList.add(apiLog);
}catch(Exception e){
ApiLog__c apiLog = new ApiLog__c();
apiLog.EndPoint__c = req.getEndpoint();
apiLog.ImageURL__c = '';
//apiLog.Prediction__c = predictionTags.get(tags);
apiLog.RequestBody__c = req.getBody();
apiLog.ResponseBody__c = res.getBody();
apiLog.SocialPost__c = spObj.Id;
apiLog.StatusCode__c = String.valueOf(res.getStatusCode());
apiLog.Type__c = 'Social Studio';
apiLogsList.add(apiLog);
}
accessTokenWithApiLog.put(accessToken, apiLogsList);
return accessTokenWithApiLog;
}
}
the full errror is:-System.NullPointerException: Attempt to de-reference a null object//
Class.ContentDocumentLinkTriggerHelper.getAccessToken: line 291, column 1
Class.ContentDocumentLinkTriggerHelperTest.AddTagsToPostTest: line 75, column 1
ApiLog__c al = new ApiLog__c();
al.Name='Test';
//Add all other fields
insert al;