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
Sony PSPSony PSP 

Test Class for Upload/Import

Hi Guys,

Can you please help me with my test class I'm only achieving 39% as of now, please do comment on some line I am just new with test classes.
 
//Test CLASS
public class ProductImportController{


    public Blob csvFileBody { get; set; }
    public String csvFileName { get; set; }
    
    public Boolean showResults { get; set; }
    public Boolean showImport { get; set; }
    public Boolean isUploading { get; set; }
    
    public List<Product2> prdctList { get; set; }
    public List<PricebookEntry> pbeListStandard  { get; set; }
    public List<PricebookEntry> pbeListCustom { get; set; }
    
    public ProductImportController(){
        //Show/hide sections
        showResults = false;
        showImport = true;
        isUploading = false;
    }
    
    public void upload(){
    
        if(isUploading){ return; }
        isUploading = true;
    
        //Show/hide sections
        showResults = true;
        showImport = false;
    
        try{
            parseCsvInsertProductsPricebooks();
        }catch(Exception e){
            ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR, e.getMessage() ));
            
            //Show/hide sections
            showResults = false;
            showImport = true;
            isUploading = false;
            
            if(Test.isRunningTest()){
                throw e;
            }else{
                return;
            }
        }
        
        //Finished
        ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.INFO, 'Product import completed.'));
        isUploading = false;
    }
    
    public void parseCsvInsertProductsPricebooks(){
        
        if(csvFileBody == null){
            throw new ProductImportException('No CSV found.');
        }
        
        //Convert from blob to string
        String csvString = csvFileBody.toString();
        csvFileBody = null;
        csvFileName = null;
        
        if(String.isBlank(csvString)){
            throw new ProductImportException('Empty CSV found.');
        }
        
        //Parse CSV into separate fields
        List<List<String>> allFields = parseCSV(csvString);
        
        if(allFields == null || allFields.isEmpty()){
            throw new ProductImportException('Empty CSV found.');
        }
                
        //Use first line as header
        List<String> headerFields = allFields.remove(0);
        List<HeaderWrapper> headerList = parseHeaders(headerFields);
        List<LineWrapper> lineList = new List<LineWrapper>();
        
        //Parse remaining lines
        if(allFields == null || allFields.isEmpty()){
            throw new ProductImportException('No rows found.');
        }else{
            for(List<String> line : allFields){
                lineList.add(new LineWrapper(line,headerList));
            }
        }
        
        //Get all products
        prdctList = new List<Product2>();
        for(LineWrapper line : lineList){
            prdctList.add(line.prdct);
        }
        
        //Insert products
        try{
            insert prdctList;
            System.debug(prdctList);
        }catch(Exception e){
            throw new ProductImportException('Could not insert products. ' + e.getMessage() ,e);
        } 
        
        
        //Insert standard pricebook entries
        pbeListStandard = new List<PricebookEntry>();
        for(LineWrapper line : lineList){
            List<PricebookEntry> l = line.getStandard();
            if(l != null){
                pbeListStandard.addAll(l);
            }
        }
        try{
            if(!pbeListStandard.isEmpty()){
                System.debug('* ** *** inserting standard pbe '  + pbeListStandard);
                insert pbeListStandard;
                System.debug(pbeListStandard);
            }
        }catch(Exception e){
            throw new ProductImportException('Could not insert pricebook entries. ' + e.getMessage() ,e);
        }
        
        //Insert custom pricebook entries
        pbeListCustom = new List<PricebookEntry>();
        for(LineWrapper line : lineList){
            List<PricebookEntry> l = line.getCustom();
            if(l != null && !l.isEmpty()){
                pbeListCustom.addAll(l);
            }
        }
        try{
            if(!pbeListCustom.isEmpty()){
                System.debug('* ** *** inserting custom pbe ' + pbeListCustom);
                insert pbeListCustom;
                System.debug(pbeListCustom);
            }
        }catch(Exception e){
            throw new ProductImportException('Could not insert pricebook entries. ' + e.getMessage(),e);
        }
    }
    
    public static List<HeaderWrapper> parseHeaders(List<String> headerFields){
    
        //List of headers
        List<HeaderWrapper> headerList = new List<HeaderWrapper>();
        
        //Mapping setting
        Map<String,ProductImportMapping__mdt> pim = new Map<String,ProductImportMapping__mdt>();
        for(ProductImportMapping__mdt p : [SELECT MasterLabel, Field__c, isProductField__c, Pricebook__c, Isocode__c FROM ProductImportMapping__mdt]){
            pim.put(p.MasterLabel,p);
        }
        
        //Field types
        Map<String, Schema.SObjectField> fieldMap  = Schema.SObjectType.Product2.fields.getMap();

        //Pricebooks
        Map<Id,Pricebook2> pbMap = new Map<Id,Pricebook2>([SELECT Id FROM Pricebook2 WHERE IsStandard = false]);
        
        Id pbStandard;
        if(Test.isRunningTest()){
            pbStandard = Test.getStandardPricebookId();
        }else{
            List<Pricebook2> pbStandardList = [SELECT Id FROM Pricebook2 WHERE IsStandard = true];
            if(pbStandardList == null || pbStandardList.isEmpty()){
                throw new ProductImportException('Could not find standard pricebook.');
            }else{
                pbStandard = pbStandardList.get(0).Id;
            }
        }
        
        //Map header
        for(String field : headerFields){
            
            //Get custom setting
            ProductImportMapping__mdt setting = pim.get(field);
            HeaderWrapper header;
            
            if(setting != null){
                if(setting.isProductField__c){
                
                    //check that field is valid and creatable
                    if(fieldMap.containsKey(setting.Field__c.toLowerCase()) && fieldMap.get(setting.Field__c.toLowerCase()).getDescribe().isCreateable()){                                        
                        
                        //create header wrapper
                        header = new HeaderWrapper();
                        header.name = field;
                        header.field = setting.Field__c;
                        header.isProductField = true;
                        header.isSkip = false;
                        header.type = String.valueOf(fieldMap.get(setting.Field__c.toLowerCase()).getDescribe().getType());
                        
                    }else{
                    
                        //skip header wrapper if no field
                        header = new HeaderWrapper();
                        header.isSkip = true;
                        
                    }
                    
                }else{
                
                    //check that pricebook is valid                    
                    Id pbId;
                    try{
                        pbId = Id.valueOf(setting.Pricebook__c);
                    }catch(Exception e){
                        throw new ProductImportException('Could not convert pricebook Id.', e);
                    }
                    if(!pbMap.containsKey(pbId)){
                        throw new ProductImportException('Id is not a custom pricebook Id');
                    }
                    
        
                    //create header wrapper
                    header = new HeaderWrapper();
                    header.name = field;
                    header.isProductField = false;
                    header.pricebook = setting.Pricebook__c;
                    header.standard = pbStandard;
                    header.isocode = setting.Isocode__c;
                    header.isSkip = false;
                    
                }
            }else{
                //skip header wrapper
                header = new HeaderWrapper();
                header.isSkip = true;
            }
        
            //add to list
            headerList.add(header);

        }//end-for
        
        return headerList;
        
    }//end parseHeaders
    
    //Parse CSV into separate fields
    public static List<List<String>> parseCSV(String contents) {
        List<List<String>> allFields = new List<List<String>>();
    
        contents = contents.replaceAll(',"""',',"DBLQT').replaceall('""",','DBLQT",');
        contents = contents.replaceAll('""','DBLQT');
        List<String> lines = new List<String>();
        try {
            lines = contents.split('\n');
        } catch (Exception e) {
            throw new ProductImportException('Could not split CSV.', e);
        }
        
        Integer num = 0;
        for(String line : lines) {
            // check for blank CSV lines (only commas)
            if (line.replaceAll(',','').trim().length() == 0) break;
            
            
            line = line.replaceAll('\r','').trim();
            
            List<String> fields = line.split(',');  
            List<String> cleanFields = new List<String>();
            String compositeField;
            Boolean makeCompositeField = false;
            for(String field : fields) {
                if (field.startsWith('"') && field.endsWith('"')) {
                    cleanFields.add(field.replaceAll('DBLQT','"'));
                } else if (field.startsWith('"')) {
                    makeCompositeField = true;
                    compositeField = field;
                } else if (field.endsWith('"')) {
                    compositeField += ',' + field;
                    cleanFields.add(compositeField.replaceAll('DBLQT','"'));
                    makeCompositeField = false;
                } else if (makeCompositeField) {
                    compositeField +=  ',' + field;
                } else {
                    cleanFields.add(field.replaceAll('DBLQT','"'));
                }
            }
            
            allFields.add(cleanFields);
        }
        
        return allFields;       
    }//end parseCSV
    
    //wrapper for line
    class LineWrapper{
        Product2 prdct;
        Map<String,PricebookEntry> pbeStandard = new Map<String,PricebookEntry>();
        List<PricebookEntry> pbeCustom = new List<PricebookEntry>();
    
        public LineWrapper(List<String> fields, List<HeaderWrapper> headerList){
            
            System.debug('* ** *** fieldsize: ' + fields.size() + '. headersize: ' + headerList.size());
            
            //Loop through every cell in row
            for(Integer ctr = 0; ctr < fields.size() && ctr < headerList.size(); ctr++){
    
                //Get value of cell and header
                String field = fields.get(ctr);
                HeaderWrapper header = headerList.get(ctr);
                
                System.debug('LineWrapper #' + ctr + ': "' + field + '" ' + header);
                
                if(header == null || header.isSkip){
                    //Do nothing
                    System.debug('* ** *** skip');
                }else if(header.isProductField && field == null){
    
                    //Field name is required
                    throw new ProductImportException('Could not identify field for line: ' + fields);
    
                }else if(header.isProductField && field != null){
    
                    //Create product
                    if(this.prdct == null){
                        this.prdct = new Product2();
                    }
    
                    //Set value of field depending on type
                    try{
                        if(header.type == 'BOOLEAN'){
                            this.prdct.put(header.field,Boolean.valueOf(field));
                        }else if(header.type == 'DATETIME'){
                            this.prdct.put(header.field,DateTime.valueOf(field));
                        }else if(header.type == 'DOUBLE'){
                            this.prdct.put(header.field,Double.valueOf(field));
                        }else if(header.type == 'BOOLEAN'){
                            this.prdct.put(header.field,Boolean.valueOf(field));
                        }else if(header.type == 'REFERENCE'){
                            this.prdct.put(header.field,Id.valueOf(field));
                        }else{
                            this.prdct.put(header.field,field);
                        }
                    }catch(Exception e){
                        throw new ProductImportException('Could not populate field ' + header.field + ' with ' + field);
                    }
    
                }else if(String.isBlank(header.isocode) || header.pricebook == null){
    
                    //Pricebook and isocode mapping required
                    throw new ProductImportException('Could not identify pricebook and currency for line: ' + fields);
    
                }else{
                    Decimal price = Decimal.valueOf(field);
                    
                    //Create custom pricebook entry
                    PricebookEntry pbe = new PricebookEntry(Pricebook2Id = header.pricebook, UnitPrice = price, IsActive = true,CurrencyIsoCode=header.isocode);
                    
                    
                    //Create standard pricebook entry
                    if(!pbeStandard.containsKey(header.isocode)){
                        pbeStandard.put(header.isocode,new PricebookEntry(Pricebook2Id = header.standard, UnitPrice = price, IsActive = true,CurrencyIsoCode=header.isocode));
                        
                        //Set custom to use standard
                        pbe.UseStandardPrice = true;
                    }
                    
                    //Add custom pricebook entry to list
                    this.pbeCustom.add(pbe);
                
                }//end if-else
    
            }//end for
    
        }//end constructor
        
        public List<PricebookEntry> getStandard(){
            for(PricebookEntry pbe : pbeStandard.values()){
                pbe.Product2Id = prdct.Id;
            }
            return pbeStandard.values();
        }
        
        public List<PricebookEntry> getCustom(){
            for(PricebookEntry pbe : pbeCustom){
                pbe.Product2Id = prdct.Id;
            }
            
            return pbeCustom;
        }
    
    }//end class

    //custom exception
    class ProductImportException extends Exception {}

    //wrapper for header
    class HeaderWrapper{
        String name;
        String field;
        String isocode;
        String type;
        Id pricebook;
        Id standard;
        boolean isProductField;
        boolean isSkip;
    }
    
}
 
//Test CLASS
@isTest
public class ProductImportController_Test {
    private static testMethod void testData()
    {
        
        Product2 prdctlist = new Product2(Name = 'Test Product004', ProductCode = 'Test Product004');
        insert prdctlist;
        
        PricebookEntry pbeListStandard =  new PricebookEntry();
        PricebookEntry pbeListCustom =  new PricebookEntry();

ApexPages.standardController(testProduct);
        ProductImportController scontroller = new ProductImportController();
        

        scontroller.csvFileName = 'Test Product';
        scontroller.csvFileBody = Blob.valueOf('Test AttachmentBody');


        scontroller.upload();
        
    }      
}

 
ShivaKrishna(Freelancer)ShivaKrishna(Freelancer)
Hi,

try pasting the screen shot that highlighting uncovered lines so that it would be easy to figure the changes to be done. 

Thanks!
shiva.sfdc.backup@gmail.com
Sony PSPSony PSP
any help for this? mostlikely i have error on exceptions
Sony PSPSony PSP
any help pls?