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
Paolo Magliocco 18Paolo Magliocco 18 

Test class InvioFatturaCtrl_Test

Hi I'm writing a test class but It covers the code only 65% of class.
Can someone help me?

Code of class is this :

public class InvioFatturaCtrl {


    public String users { get; set; }
    public String toAddresses {get; set;}
    public String ccAddresses {get; set;}
    public String ccnAddresses {get; set;}
    public String testomail {get; set;}
    public String emailUserTo {get; set;}
    public String emailUserCc {get; set;}
    public String emailUserCcn {get; set;}
    public Boolean emailSent {get; private set;}
    public PageReference thePDF {public get; public set;}
    
    public Fattura__c fatt {get; set;}
    public Integer pageNum { get; set; }
   // public List<QuoteLineItem> l_qtl{get; set;}
   // public List<Partecipazione__c> l_ptz{get; set;}
  //  public List<Riga_Fattura__c> l_rfat{get; set;}
    public Integer dim_qtl = 0;
    public Pagereference Fattura {get;set;}


    public String getCcAddresses() {
        return null;
    }

    


    List<SelectOption> Options= new List<SelectOption>();
    public String scelta {get;set;}  // conterrà il valore selezionato/scelto da Options
    
    public List<SelectOption> getOptions(){   // mi popola la variabile Options con i 2 valori si no 
       List<SelectOption> opt = new List<SelectOption>();
       opt.add(new SelectOption('NO','NO'));
       opt.add(new SelectOption('SI','SI'));
       return opt;
    }
   
   
    public void registerUser() {  // incremento il numero della pagina da visualizzare ogni volta che clicco sul tasto AVANTI
      
      pageNum++;
    }

    
    
     public InvioFatturaCtrl(ApexPages.StandardController stdcontroller) {
     pageNum = 1;
     this.fatt = (Fattura__c)stdController.getRecord();
     this.fatt = [Select id,name,Preventivo__r.Training__c,Preventivo__r.Consulenza__c, Preventivo__r.Opportunity.AccountId,Preventivo__r.Opportunity.Account.Owner.name, Preventivo__r.Opportunity.Account.Descrizione_IVA_def__c,Preventivo__r.Opportunity.Account.Note_esenzione_IVA__c, Preventivo__r.Banca__r.name,Preventivo__r.Banca__r.Conto_corrente__c, Preventivo__r.Banca__r.ABI__c, Preventivo__r.Banca__r.CAB__c , Preventivo__r.Banca__r.IBAN__c, Preventivo__r.Opportunity.Account.Name,Preventivo__r.Opportunity.Account.BillingStreet,Preventivo__r.Opportunity.Account.BillingCity,Preventivo__r.Opportunity.Account.BillingState,Preventivo__r.Opportunity.Account.BillingPostalCode, Preventivo__r.Opportunity.Account.Partita_IVA__c , preventivo__c  from fattura__c where id =:stdController.getRecord().id];
     if(fatt.Preventivo__r.Training__c == true){
            fattura = page.Fattura_Standard;
        }
        else if (fatt.Preventivo__r.Consulenza__c == true){
            fattura = page.Fattura_Consulenza;
        } 
        system.debug('****test'+fattura );
     }
    
    
    public String addEmailAddress(String email, String emailAddresses) {
        
        if(String.isBlank(email)){
          return emailAddresses;
         }
         
        if(emailAddresses == null) {
          emailAddresses = '';
         }
         
        List<String> listOfEmail = emailAddresses.split(';');
        listOfEmail.add(email);
        
        Set<String> listOfUniqueEmail = new Set<String>();
        listOfUniqueEmail.addAll(listOfEmail);
        emailAddresses = '';
        for(String e : listOfUniqueEmail)
            if(String.isNotBlank(e)){
                emailAddresses += e + ';';
            }
        emailAddresses = emailAddresses.removeEnd(';');
        return emailAddresses;
    }
 
 
    
    public void addToAddresses()  { 
        toAddresses  = addEmailAddress(emailUserTo, toAddresses);   
    }
    
    public void addCcAddresses()  { 
       ccAddresses  = addEmailAddress(emailUserCc, ccAddresses);   
    }
   
    public void addCcnAddresses() { 
       ccnAddresses = addEmailAddress(emailUserCcn, ccnAddresses); 
    } 
    
   
   
   public Attachment createPDF() {
        thePDF = Fattura;
        thePDF.getParameters().put('Id', fatt.Id);
        system.debug('***thePDF'+thePDF);
        attachment qd=new attachment();
        if(!Test.isRunningTest()){            qd.Body = thePDF.getContentAsPDF();        } else {
            Blob blab = Blob.valueOf('Test Data');
            qd.Body = blab;
        }
        system.debug('***qd.Body'+qd.Body);
      qd.ContentType = 'application/pdf';     
      qd.Name = fatt.name +'.pdf';
      return qd;
      }
      

 public pageReference invia() {
        Boolean validate = true;
        if(String.isBlank(toAddresses)) {
            validate = false;
            ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR, 'Specificare indirizzo e-mail'));
        }
        if(String.isBlank(testomail)) {
            validate = false;
            ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR, 'Specificare testo e-mail'));
        }
        
        List<String> toAddressesList  = new List<String>();
        List<String> ccAddressesList  = new List<String>();
        List<String> ccnAddressesList = new List<String>();
        if(!String.isBlank(toAddresses))  toAddressesList  = toAddresses.split(';');
        if(!String.isBlank(ccAddresses))  ccAddressesList  = ccAddresses.split(';');
        if(!String.isBlank(ccnAddresses)) ccnAddressesList = ccnAddresses.split(';');
        
       // if(!validate) { return Apexpages.currentPage(); }
        //  else{ return NULL;}
                
        String subject = 'Fattura da inviare'; // ' + fatt.Preventivo__r.Opportunity.Account.name + ' - ' + fatt.Name;
    //  testomail = 'questo è il testo della mail';
        String body = testomail /*.replaceAll('\n','<br/>')*/;
        
        Messaging.EmailFileAttachment allegatoEmail = new Messaging.EmailFileAttachment();
        Attachment qd = createPDF();
        system.debug('****test'+qd );
        
        allegatoEmail.setBody(qd.Body);
        allegatoEmail.setFileName(qd.Name);
        allegatoEmail.setContentType(qd.ContentType);
        system.debug('****test'+allegatoEmail );

        list<Messaging.EmailFileAttachment> allegatiEmail = new list<Messaging.EmailFileAttachment>();
        allegatiEmail.add(allegatoEmail);
        
        
        
        messaging.SingleEmailMessage mail = new messaging.SingleEmailMessage();
            mail.setCcAddresses(ccAddressesList);
            mail.setToAddresses(toAddressesList);
            mail.setBccAddresses(ccnAddressesList);
            mail.setSubject(subject);
            mail.setHTMLBody(testomail);
            mail.setFileAttachments(allegatiEmail);
            system.debug('****test'+mail );
            list<messaging.SingleEmailMessage> mails = new list<messaging.SingleEmailMessage>{mail};
           
        
        emailSent = TRUE;
        List<messaging.sendemailresult> results = messaging.sendEmail(mails);
       
        
        qd.ParentId = fatt.Id;
        List<Attachment>qds = new List<Attachment>();
        qds.add(qd);
        try{
            insert qds;
          //  quo.Status = 'Attiva';
          //  update quo;
        }catch (DMLexception e) {
            ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR, 'Eccezione DML nell\'upload dell\'allegato: ' + e));
        }
        ApexPages.addMessage(new ApexPages.message(ApexPages.severity.INFO,'Allegato caricato!'));
         
        //return NULL;
        return new PageReference('/'+fatt.id);

    }
 
 }


Code of test class is this : 

@isTest

public class Invio_FatturaCtrl_Test {
    static testMethod void Costruttore_Test()
    {

 /*******************************************************************  START TEST   ***********************************************************************************************/      
 
      test.startTest();
      
      List<SelectOption> Options= new List<SelectOption>();
      
      Account acc = new Account();
      acc.name='Test Account';
      acc.billingStreet='via bo';
      acc.billingCity='Torino';
      acc.billingState='Ecuador';
      acc.billingCountry='Italy';
      insert acc;
        
      Opportunity opp = new Opportunity();
      opp.Accountid = acc.id;
      opp.Name = 'test';
      opp.StageName = 'Prospecting';
      opp.CloseDate = date.today();
      opp.Type = 'New Client';
      opp.NextStep = 'Test';
      opp.LeadSource = 'Business Development';
      insert opp;
      
      Product2 prod = new Product2 ();
      prod.name='test';
      prod.IsActive=true;
      insert prod;

      Id pricebookId = Test.getStandardPricebookId();
      PricebookEntry pbe = new PricebookEntry ();
      pbe.Product2Id=prod.Id;
      pbe.IsActive=true;
      pbe.UnitPrice=1;
      pbe.Pricebook2Id=pricebookId;
      insert pbe;
      
      Quote offerta = new Quote();
      offerta.Name = 'soldi';
      offerta.N_Offerta__c = '9cento';
      offerta.OpportunityId = opp.id;
      offerta.Pricebook2Id = pricebookId ;
      insert offerta;
        
      Fattura__c fat = new Fattura__c();
      fat.Preventivo__c = offerta.id;
      insert fat;
      List<Fattura__c> l_fat = new List<Fattura__c>();
      l_fat.add(fat);
      
      
      messaging.SingleEmailMessage messg_mail = new messaging.SingleEmailMessage();
      //mail.setCcAddresses(ccAddressesList);
      Messaging.EmailFileAttachment allegatoEmail = new Messaging.EmailFileAttachment();
      attachment alleg =new attachment();
      alleg.ParentId = fat.id ;
      alleg.Name = 'non mi interessa';
      alleg.Body = Blob.valueOf('/services/data/v38.0/sobjects/Attachment/'+fat.id+'/Body');
      insert alleg;
      
      List<messaging.SingleEmailMessage> l_mail = new list<messaging.SingleEmailMessage>{messg_mail};
      Set<String> l_mail_univoche = new Set<String>();
      List<Messaging.EmailFileAttachment> l_allegati = new list<Messaging.EmailFileAttachment>();
      
      List<String> toAddressesList  = new List<String>();
      List<String> ccAddressesList  = new List<String>();
      List<String> ccnAddressesList = new List<String>();
    
      List<String> l_indirizzi_dest  = new List<String>();
      List<String> l_indirizzi_copia  = new List<String>();
      List<String> l_indir_copianascosta = new List<String>();
      String scelta = 'scegli me';
      
      
     ApexPages.StandardController controller = new ApexPages.StandardController(fat);
     InvioFatturaCtrl stdController = new InvioFatturaCtrl(controller);
     
     String email = 'senza soldi non si canta messa';
     String emailAddresses = 'babbo@natale.it';
     stdController.getCcAddresses();
     stdController.getOptions();
     stdController.registerUser();
     stdController.addEmailAddress(email,emailAddresses);
     stdController.addToAddresses(); 
     stdController.addCcAddresses();
     stdController.addCcnAddresses();
     stdController.invia();
     stdController.createPDF();

 


/******************************************************************* FINISH TEST   ***********************************************************************************************/      
 
   test.stopTest();

   }
  
 }
Amit Chaudhary 8Amit Chaudhary 8
Try to add below flag
      offerta.Training__c = true;
      offerta.Consulenza__c = true;

Please update your test class like below. Let us know which line are not covered
@isTest

public class Invio_FatturaCtrl_Test {
    static testMethod void Costruttore_Test()
    {

 /*******************************************************************  START TEST   ***********************************************************************************************/      
 
      test.startTest();
      
      List<SelectOption> Options= new List<SelectOption>();
      
      Account acc = new Account();
      acc.name='Test Account';
      acc.billingStreet='via bo';
      acc.billingCity='Torino';
      acc.billingState='Ecuador';
      acc.billingCountry='Italy';
      insert acc;
        
      Opportunity opp = new Opportunity();
      opp.Accountid = acc.id;
      opp.Name = 'test';
      opp.StageName = 'Prospecting';
      opp.CloseDate = date.today();
      opp.Type = 'New Client';
      opp.NextStep = 'Test';
      opp.LeadSource = 'Business Development';
      insert opp;
      
      Product2 prod = new Product2 ();
      prod.name='test';
      prod.IsActive=true;
      insert prod;

      Id pricebookId = Test.getStandardPricebookId();
      PricebookEntry pbe = new PricebookEntry ();
      pbe.Product2Id=prod.Id;
      pbe.IsActive=true;
      pbe.UnitPrice=1;
      pbe.Pricebook2Id=pricebookId;
      insert pbe;
      
      Quote offerta = new Quote();
      offerta.Name = 'soldi';
      offerta.N_Offerta__c = '9cento';
      offerta.OpportunityId = opp.id;
      offerta.Pricebook2Id = pricebookId ;
	  offerta.Training__c = true;
	  offerta.Consulenza__c = true;
      insert offerta;
        
      Fattura__c fat = new Fattura__c();
      fat.Preventivo__c = offerta.id;
      insert fat;
      List<Fattura__c> l_fat = new List<Fattura__c>();
      l_fat.add(fat);
      
      
      messaging.SingleEmailMessage messg_mail = new messaging.SingleEmailMessage();
      //mail.setCcAddresses(ccAddressesList);
      Messaging.EmailFileAttachment allegatoEmail = new Messaging.EmailFileAttachment();
      attachment alleg =new attachment();
      alleg.ParentId = fat.id ;
      alleg.Name = 'non mi interessa';
      alleg.Body = Blob.valueOf('/services/data/v38.0/sobjects/Attachment/'+fat.id+'/Body');
      insert alleg;
      
      List<messaging.SingleEmailMessage> l_mail = new list<messaging.SingleEmailMessage>{messg_mail};
      Set<String> l_mail_univoche = new Set<String>();
      List<Messaging.EmailFileAttachment> l_allegati = new list<Messaging.EmailFileAttachment>();
      
      List<String> toAddressesList  = new List<String>();
      List<String> ccAddressesList  = new List<String>();
      List<String> ccnAddressesList = new List<String>();
    
      List<String> l_indirizzi_dest  = new List<String>();
      List<String> l_indirizzi_copia  = new List<String>();
      List<String> l_indir_copianascosta = new List<String>();
      String scelta = 'scegli me';
      
      
     ApexPages.StandardController controller = new ApexPages.StandardController(fat);
     InvioFatturaCtrl stdController = new InvioFatturaCtrl(controller);
     
     String email = 'senza soldi non si canta messa';
     String emailAddresses = 'babbo@natale.it';
     stdController.getCcAddresses();
     stdController.getOptions();
     stdController.registerUser();
     stdController.addEmailAddress(email,emailAddresses);
     stdController.addToAddresses(); 
     stdController.addCcAddresses();
     stdController.addCcnAddresses();
     stdController.invia();
     stdController.createPDF();

 


/******************************************************************* FINISH TEST   ***********************************************************************************************/      
 
   test.stopTest();

   }
  
 }

Let us know if this will help u
Paolo Magliocco 18Paolo Magliocco 18
Thank you very much Amit :)