0

I have written a Batch apex.The Batch Apex class call the Helper (web service )class.I have written a test class for Batch apex.But my Helper (web service )class is covered with 99%.To cover the Batch class i have added

 Test.StartTest();
 ProductDetailsNew_CLS Capture = new ProductDetailsNew_CLS();
 Database.executeBatch(Capture ,1);
 Test.StopTest();

this lines in my test class.

Batch class:

public class ProductDetailsNew_CLS implements Database.Batchable<List<String>>, Database.AllowsCallouts {
public string strJSON{get;set;}
public string strGeturl;
public string strGetcountrycode;
public string strGetCurrency;
public string strDocURL;
public string brand;
public string strScpModel;

public list<string> lstcalOut=new list<string>(); 
public List<List<String>> lsturlData; 
public List<String> lstc2gData; 
public ProductValuesNew_CLS prodData=new ProductValuesNew_CLS();
public List<product2> lstVersionProd ; 
public List<product2> lstModelProd ; 


public Map<string,String> mVersionIdScrCode = new Map<string,String>();
public Map<string,String> mVersionIdlabel = new Map<String, String>(); 


//Getting values from Custom settings
public ProductDetailsNew_CLS(){
        allCountryInfo__c cs = allCountryInfo__c.getInstance('DZ');
        strGeturl= cs.C2GURL__c;
        strGetcountrycode=cs.name;
        strGetCurrency=cs.Currency__c;
    }

public Iterable<List<String>> start(Database.BatchableContext BC) {
    lstcalOut=prodData.getJSONFromREST(strGeturl);
    lsturlData= new List<List<String>>();
    for(String strDataUrl:lstcalOut) {
        lstc2gData= prodData.getData(strDataUrl);
        lstc2gData.add(strDataUrl);
        lsturlData.add(lstc2gData);
    } 
    system.debug('<<<<<<<lsturlData'+lsturlData+'::::::'+lsturlData.size());
    return lsturlData ;   
}
public void execute(Database.BatchableContext BC, List<List<String>> records) {
    lstVersionProd = new List<product2>();
    lstModelProd = new List<product2>();
    for(List<String> d:records) {

        strScpModel= prodData.getModelScpLabel(d[8]); 
        mVersionIdScrCode=prodData.getVersionIdScrCode(d[9]);  
        mVersionIdlabel=prodData.getVersionidScp(d[8]); 
        List<List<String>> lstVersionIdLabelCode=prodData.getVersionIdLabelCode(mVersionIdlabel,mVersionIdScrCode); 
        for(List<string> p:lstVersionIdLabelCode) { 
            Product2 newProd=new product2(); 
            brand=d[4];
            newProd.CurrencyIsoCode=strGetCurrency;  
            newProd.ProductCode=p[2];
            newProd.name=strGetcountrycode+'-'+strScpModel+'-'+p[1];
            newProd.SCP_code__c=p[2];
            newProd.SCP_Label__c=p[1]; 
            newProd.Country_code__c=strGetcountrycode;
            if(brand=='APL03'){brand='Renault';}
            if(brand=='APL05'){System.debug('brand<<<<<<<<<<'+brand);brand='Dacia';}
            newProd.Brand__c=brand;
            newProd.VersionCombination__c=strGetcountrycode+brand+p[2]+strScpModel+p[0];
            newProd.C2G_version_code__c=p[0];
            newProd.Description=strGetcountrycode+'-'+brand+'-'+p[2]+strScpModel;  
            newProd.C2GParentProduct__c=strGetcountrycode+'-'+strScpModel;
            newProd.IsActive=true;
            lstVersionProd.add(newProd);  
        } 
        Product2 newProd=new product2(); 
        brand=d[4];  
        newProd.ProductCode=d[2];
        newProd.Family=d[0];
        newProd.name=strGetcountrycode+'-'+strScpModel;
        if(brand=='APL03'){brand='Renault';}
        if(brand=='APL05'){brand='Dacia';}
        newProd.Brand__c=brand;
        newProd.Country_code__c=strGetcountrycode;
        newProd.Market__c=d[3];
        newProd.CurrencyIsoCode=strGetCurrency; 
        newProd.phase__c=d[1];
        newProd.SCP_code__c=d[5];
        newProd.SCP_Label__c=strScpModel;
        newProd.ModelCombination__c=strGetcountrycode+'-'+brand+'-'+d[1]+'-'+d[2];
        newProd.Description=strGetcountrycode+'-'+brand+'-'+d[1]+'-'+d[2];
        newProd.IsActive=true;
        lstModelProd.add(newProd);                      
    }   
    try {
        upsert  lstModelProd ModelCombination__c;
        upsert lstVersionProd VersionCombination__c;
    }    
    catch (DMLException e){
        System.debug('retry!'); 
    }
}
public void finish(Database.BatchableContext BC){}

}

Helper class(Webservice class):

public class Rfleet_DZC2GProductValuesNew_CLS {

public string strJSON;
public string strDocURL ;
public string strModelScp;
public string strC2gVerid;
public string strVersionScr;
public String strVersionId;
public String strVersionScp;
public String strVersion;
Set<String> setVersionID;
public Rfleet_JSON2C2GMainURL_CLS obj = null;
public List<Rfleet_JSON2C2GMainURL_CLS.Docs> lstDocs;
public list<string> lstC2GUrl=new list<string>(); //contains all doc url
List<string> lstVersionIdC2G=new list<string>(); //C2G version Ids  
List<string> lstVersionScr=new list<string>();   //C2G version SCR codes
Map<string,string> mapVersionIdScr=new map<string,string>(); //C2G version Ids and SCR codes
Map<String, String> mapVersionIdScp = new Map<String, String>(); //Version Id and SCP 
List<String> lstcalOut = new List<String>();  //Inner callout values
List<List<String>> lstVersionIdLabelCode= new List<List<String>>(); //Final Version ID,SCP Label,SCR Code
public Rfleet_JSONC2GDocURL_CLS docObj=null;
public Rfleet_JSONC2GMarketingMoelURL_CLS objModel=null;

//Common method to Parse the JSON
public String init(String strURL) {
    try {
        Http http = new Http();
        HttpRequest httpReq = new HttpRequest();
        httpReq.setEndpoint(strURL);
        httpReq.setHeader('Accept','application/JSON');
        httpReq.setMethod('GET');
        HttpResponse response = http.send(httpReq);
        strJSON= response.getBody();
    }catch (Exception ex) {
        system.debug('<<Method: init Exception ::'+ ex);
    } 
    return  strJSON;     
}
//Used to get DOCURL's
public List<String> getJSONFromREST(String strGeturl) {
    strJSON= init(strGeturl);
    obj = Rfleet_JSON2C2GMainURL_CLS.parse(strJSON);
    lstDocs=obj.Docs; 
    for(Rfleet_JSON2C2GMainURL_CLS.Docs strDocs:lstDocs){
    strDocURL=strDocs.doc;
    lstC2GUrl.add(strDocURL);
    }
    system.debug('<<<<<<<lstcalOut'+lstC2GUrl+'::::::'+lstC2GUrl.size());   
    return lstC2GUrl;
}


// Inner callout,getting values of product from c2g
public List<String> getData(String url) {
        strJSON= init(url);
        docObj= Rfleet_JSONC2GDocURL_CLS.parse(strJSON);
        lstcalOut = new List<String>();
        String strProgram=docObj.DocId.program;
        String strPhase=docObj.DocId.phase;
        String strModelId=docObj.DocId.modelSpecCode;
        String strCommericalKind=docObj.DocId.commercialKind;
        String strBrand=docObj.DocId.brand;
        String strLocalSemiclair=docObj.DocId.localSemiclair;
        String strLocalSemiclairURL=docObj.DiversityData.localSemiclair;
        String strVersionsCategories=docObj.DiversityData.versionsCategories;
        String strMarketingModelPresentation=docObj.PresentationData.marketingModelPresentation;
        lstcalOut.add(strProgram);
        lstcalOut.add(strPhase);
        lstcalOut.add(strModelId);
        lstcalOut.add(strCommericalKind);
        lstcalOut.add(strBrand);
        lstcalOut.add(strLocalSemiclair);
        lstcalOut.add(strLocalSemiclairURL);
        lstcalOut.add(strVersionsCategories);
        lstcalOut.add(strMarketingModelPresentation);
        system.debug('<<<<<<<lstcalOut'+lstcalOut+'::::::'+lstcalOut.size());
        return lstcalOut;
}

//Getting Model label(SCP label)
public String getModelScpLabel(String url) {

    strJSON =init(url);
    objModel=Rfleet_JSONC2GMarketingMoelURL_CLS.parse(strJSON);
    Rfleet_JSONC2GMarketingMoelURL_CLS.MarketingModelPresentation marketingModelObj ; 
    marketingModelObj = objModel.MarketingModelPresentation;
    Rfleet_JSONC2GMarketingMoelURL_CLS.Label labelobj =  marketingModelObj.Label;
    strModelScp=labelobj.fr;
    system.debug('<<<<<<<strModelScp'+strModelScp);
    return strModelScp;
}


//Getting Version C2GId, Version SCR code

public Map<string,String> getVersionIdScrCode(String url){
    Http h = new Http();
    HttpRequest req = new HttpRequest();
    req.setEndpoint('http://dz.co.rplug.renault.com/combinations?docuri='+url+'&scc=VersionId&scc=970&scc=004'); 
    req.setHeader('Accept','application/JSON');
    req.setMethod('GET');
    HttpResponse res = h.send(req); 
    strJSON= res.getBody();
    JSONParser parser = JSON.createParser(strJSON);
        while (parser.nextToken() != null) {
            if (parser.getCurrentToken() == JSONToken.FIELD_NAME) {
                String fieldName = parser.getText();
                    if(fieldName == 'VersionId') { 
                        parser.nextToken();
                        strC2gVerid= parser.getText();
                        lstVersionIdC2G.add(strC2gVerid);
                    } 
                    if(fieldName == '004') {
                        parser.nextToken();
                        strVersionScr= parser.getText();
                        lstVersionScr.add(strVersionScr);
                    } 
            }
        } 
            for(integer i=0;i<lstVersionIdC2G.size();i++) {
              mapVersionIdScr.put(lstVersionIdC2G.get(i),lstVersionScr.get(i));
            }
   // system.debug('mapVersionIdScr===>'+mapVersionIdScr);
   // system.debug('mapVersionIdScr size===>'+mapVersionIdScr.size());
    return mapVersionIdScr;
}

//Getting Version Id and Version label(SCP label)
public Map<string,String> getVersionidScp(String url){
    strJSON =init(url);
    JSONParser parser = JSON.createParser(strJSON);
    objModel=Rfleet_JSONC2GMarketingMoelURL_CLS.parse(strJSON);
    Rfleet_JSONC2GMarketingMoelURL_CLS.MarketingModelPresentation marketingModelObj ; 
    marketingModelObj = objModel.MarketingModelPresentation;
    List< Rfleet_JSONC2GMarketingMoelURL_CLS.VersionsPresentation> lstVersionPresent;
    lstVersionPresent=marketingModelObj.VersionsPresentation;
    for(Rfleet_JSONC2GMarketingMoelURL_CLS.VersionsPresentation lstVersionPresentation: lstVersionPresent) {
        Rfleet_JSONC2GMarketingMoelURL_CLS.PresentationGroup_W presentationObjW ;
        List<Rfleet_JSONC2GMarketingMoelURL_CLS.Items_Y> lstItemY ;
        presentationObjW =lstVersionPresentation.presentationGroup;
        lstItemY =presentationObjW.items; 
        for(Rfleet_JSONC2GMarketingMoelURL_CLS.Items_Y lstItemsY:lstItemY )
        {
            Rfleet_JSONC2GMarketingMoelURL_CLS.PresentationGroup_X presentationObjX ;
            presentationObjX  = lstItemsY.presentationGroup;
            List<Rfleet_JSONC2GMarketingMoelURL_CLS.Items_Z> lstItemZ ;
            lstItemZ = presentationObjX.items;  
            for(Rfleet_JSONC2GMarketingMoelURL_CLS.Items_Z lstItemsZ:lstItemZ ) {
                Rfleet_JSONC2GMarketingMoelURL_CLS.VersionItem versionItemValue;
                versionItemValue =lstItemsZ.versionItem;   
                strVersionId= versionItemValue.versionIdSpecCode;    
                Rfleet_JSONC2GMarketingMoelURL_CLS.Label labelObj;
                labelObj=versionItemValue.label;
                strVersionScp=labelObj.fr;
                system.debug('versionItem >>>>>'+strVersionId+'--'+strVersionScp);
                if(strVersionId!=null || strVersionId!='')
                mapVersionIdScp.put(strVersionId,strVersionScp);
            }
        }
    }
    return mapVersionIdScp;
}

//Getting Final Version ID,SCP Label,SCR Code
public List<List<String>> getVersionIdLabelCode(Map<string,string> versionIdLabel,Map<string,string>versionIdCode) {
    setVersionID=versionIdLabel.keySet();
    Iterator<String> i=setVersionID.iterator();
        for(String strIds:setVersionID){ 
            if(versionIdCode.containsKey(strIds)) {      
                while(i.hasNext()) {
                    list<string> Versiondetails=new list<string>();
                    String Versionid=i.next();
                    String VersionLabel=versionIdLabel.get(Versionid);
                    String VersionScpCode=versionIdCode.get(Versionid);
                    Versiondetails.add(Versionid);
                    Versiondetails.add(VersionLabel);
                    Versiondetails.add(VersionScpCode);
                    lstVersionIdLabelCode.add(Versiondetails);
                }
            }
        }
  //  system.debug('lstVersionIdLabelCode===>'+lstVersionIdLabelCode);
  //  system.debug('lstVersionIdLabelCode size===>'+lstVersionIdLabelCode.size());
    return lstVersionIdLabelCode;
}

}

This class is covered with 99%

My test class:

@isTest
public class ProductDetailsNew_CLS_Test {
static testmethod void test() {
  allCountryInfo__c cs = new allCountryInfo__c(name= 'DZ' ,CountryName__c = 'Algeria' , C2GURL__c = 'http://dz.co.rplug.sample.com/range', Currency__c = 'DZD');
    insert cs;
    Test.StartTest();
    ProductValuesNew_CLS productController=new ProductValuesNew_CLS ();
    Test.setMock(HttpCalloutMock.class, new Rfleet_C2GMain_MockHttpResponseGenerator ()); //mock for getJsonfromRest method   
    ProductDetailsNew_CLS Capture = new ProductDetailsNew_CLS();
    ID batchprocessid = Database.executeBatch(Capture);
    Test.StopTest();
}
}

My problem is that I am getting a NullPointerException with this stack trace:

ProductValuesNew_CLS.getData: line 58, column 1 ProductDetailsNew_CLS.start: line 35, column 1

Keith C
  • 135,775
  • 26
  • 201
  • 437
uma451
  • 809
  • 7
  • 19
  • 36
  • Can you clarify what the problem is here? – Keith C Mar 21 '16 at 09:27
  • My test class got failed.Shwing error with null pointer Exception@keith – uma451 Mar 21 '16 at 09:31
  • If you supply the stack trace (all the line numbers) reported as part of the exception there is a chance someone might be able to help you. – Keith C Mar 21 '16 at 09:41
  • @keith I have posted the stack trace – uma451 Mar 21 '16 at 09:46
  • in the test class, you should be passing the expected JSON response as an argument to the mock generator's constructor so it can return that response for the specific test use case. – cropredy Mar 21 '16 at 17:16
  • @cropredy I have changed my test class by passing the expected JSON as an argument.updated my test class.Here in the helper class "getData" is called inside the response is coming .but after that it is not executed. – uma451 Mar 22 '16 at 04:05

1 Answers1

1

You get a NullPointerException with message "null input to JSON parser" from line 15 when the JSON string argument to that method is null. In a test it is the mock classes that are responding to the HTTP requests. My guess would be that one of those is throwing an exception and so leaving strJSON null.

I suggest you remove the try/catch from Rfleet_DZC2GProductValuesNew_CLS.init so that the error propagates and you can see it and so fix it via the stack trace information that you get.

Keith C
  • 135,775
  • 26
  • 201
  • 437
  • now am getting "Stack Trace Class.ProductValuesNew_CLS.getData: line 58, column 1 Class.ProductDetailsNew_CLS.start: line 35, column 1 " this error – uma451 Mar 21 '16 at 10:26
  • @uma451 There is so much code involved here that you are going to have to figure this out yourself by using the information from the exceptions and adding debug output to check the values involved. – Keith C Mar 21 '16 at 10:35
  • ,As you said i tried to remove try/catch and seen the error. – uma451 Mar 30 '16 at 04:14
  • And from the frst method getJSONFromREST am getting list of 10 URl's.In the getData method the init() function is there.for that function the url is not passed.Thats y it is null.How to pass one url from the list of 10 url's.Please show me the way !! -Keith C – uma451 Mar 30 '16 at 04:17
  • @uma451 Sorry but I don't follow what is going on in the code you have posted. Generally, you would use a for loop to go through the items in a list and pass one at a time. – Keith C Mar 30 '16 at 07:39
  • I used a for loop an d iterated it.But the response is null. - @Keith C – uma451 Mar 30 '16 at 08:43
  • how to use muliple mockclass in test class ? -@Keith C – uma451 Mar 31 '16 at 11:23
  • @uma451 You can only register one HttpCalloutMock so that single implementation will need to examine the request and assert and return a response appropriately for each request. – Keith C Mar 31 '16 at 12:57
  • @ Keith C Yes,Keith.I have multiple callouts.How to handle muliple callouts in a single HttpCalloutMock ? – uma451 Apr 01 '16 at 05:10
  • @uma451 Best ask that as a separate question if you want a more detailed answer. Its basically just if/elseif/else logic in the HttpCalloutMock. – Keith C Apr 01 '16 at 07:41
  • @ keith C. I have asked the seperate question.Please help me out to handle multicallouts !! – uma451 Apr 01 '16 at 08:38
  • http://salesforce.stackexchange.com/questions/116375/how-to-handle-multi-callout-in-test-class – uma451 Apr 01 '16 at 08:38