• scox67
  • NEWBIE
  • 5 Points
  • Member since 2013
  • Senior Developer
  • Xede Consulting Partners


  • Chatter
    Feed
  • 0
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 0
    Questions
  • 9
    Replies
Having trouble determing how to write a Test class for my Lightning Controller.  
public with sharing class NewAcctCustController  {
	
	@AuraEnabled
	public static List<String> getStates() {
		List<String> stateList = new List<String> {'AL', 'AK', 'AZ', 'AR', 'UT', 'VT', 'VA', 'WA', 'WV', 'WI', 'WY'};

		return stateList;
	}
   
	@AuraEnabled
	public static List<String> getPicklistOptionsforCust() {
		return getPicklistValues('Customer__c', 'Cust_Type__c');
	}
	public static List<String> getPicklistValues(String objectAPI, String fieldAPI) {
		List<String> picklistValues = new List<String>();
		List<Schema.PicklistEntry> values = Schema.getGlobalDescribe().get(objectAPI).getDescribe().fields.getMap().get(fieldAPI).getDescribe().getPicklistValues();

		for (Schema.PicklistEntry val : values) {
			picklistValues.add(val.getLabel());
		}
		return picklistValues;
	}
	
	@AuraEnabled
	public static string  submitObjecttoApex(sObject acct, sObject cust,sObject proj) 
	{ 
		try {
			Account__c oacct = (Account__c)acct;
			Customer__c ocust = (Customer__c)cust;
			Customer_Project oproj = (Customer_Project__c)proj;

			oacct.Project_Type__c = 'New Customer';
			insert acct;
			Decimal custnum = oacct.Customer_num__c;						
						
			List<acct__Project_Template__c> template = [SELECT Id FROM Project_Template__c WHERE Name = 'New Potential Customer' LIMIT 1];
			if (template != null && template.size() > 0) 
			{
				ocust.ProjectTemplate__c = template[0].Id;
			}			
				ocust.Account__c = oacct.Id;		
				insert cust;
				
				oproj.Customer__c = ocust.Id;		

				Customer_Project existingcustproj = [select id from Customer_Project__c where Project__c =: oproj.Id limit 1];
								
				existingcustproj.CompType= oproj.CompType__c;
				existingcustproj.Type= oproj.CustProj__c;
				existingcustproj.Apptype= oproj.App_Type__c;
				
				update existingcustproj;		
		} 
	}
}
The requirement is to fire trigger in case of record update, but do not want to update record in-case of mass update i.e. bulk update via data loader. 
I am a beginner in apex. I have written this kind of test, but it makes some mistakes, someone can tell me what is wrong or how to do it better.
I only have 60% coverage...

User-added image
The contacts to which a template with an attached file will be sent are selected.
The file is not mandatory.
In the custom button, only the subject and body are written and the template is not taken.

These are my codes.
****Visualforce*****
<apex:page controller="ControllerEnviaEmailInscripciones" doctype="html-5.0" language="es"> 
    <apex:form id="frm" acceptcharset="UTF-8">
      <apex:pageBlock >
          
          <apex:pageBlockSection columns="1">
              <apex:pageBlockTable value="{!models}" var="m">
                <apex:column headerValue="Acción" >
                    <apex:inputcheckbox value="{!m.flag}"/> 
                </apex:column>
                <apex:column headerValue="Nombre de la Inscripción">
                       <apex:outputField value="{!m.std.Name}"/>
                </apex:column>
                <apex:column headerValue="Contacto">
                         <apex:outputField value="{!m.std.Contacto__r.Name}"/>
                </apex:column>
                <apex:column headerValue="Cliente">
                        <apex:outputField value="{!m.std.Cliente__r.Name}"/> 
                </apex:column>
                <apex:column headerValue="Email">
                       <apex:outputField value="{!m.std.CorreoElectronico__c}"/>
                </apex:column>
                <apex:column headerValue="Número de Inscripción">
                        <apex:outputField value="{!m.std.NumeroInscripcion__c}"/>
                </apex:column>  
                <apex:column headerValue="Estado">
                        <apex:outputField value="{!m.std.Estado__c}"/>
                </apex:column>
              </apex:pageBlockTable>      
          </apex:pageBlockSection>
          
           <apex:pageBlock > 
        <!--  <apex:outputLabel value="Nombre del Archivo" for="fileName"/>
              <apex:inputText value="{!attachment.name}" id="fileName"/> -->
              <apex:outputLabel value="Archivo" for="file"/>
              <apex:inputFile value="{!attachment.body}" filename="{!attachment.name}" id="file" />
              <apex:messages style="font-size: 100%; color: blue;"/>
           </apex:pageBlock> 
       <!------------------------Sección de Email Personalizado--------------------------->  
           <apex:pageBlock > 
              <apex:commandButton value="{!Personalizaremail}" action="{!click}"/>     
                
               <apex:pageBlockSection id="thePanel" rendered="{!thePanel}">
                  <apex:pageBlockSectionItem >
                      <a style="font-family: Arial; font-size: 10pt;">Asunto:</a>
                      <apex:inputText value="{!asunto}" style="font-family: Arial; font-size: 10pt;" size="80" /> 
                  </apex:pageBlockSectionItem><br/> 
                  
                  <apex:pageBlockSectionItem >&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                  	  <apex:inputTextarea value="{!texto}" rows="15" cols="91" lang="es"/> <!-- lang="es" richText="true"-->
                  </apex:pageBlockSectionItem><br/>
               </apex:pageBlockSection> 
               
           </apex:pageBlock> 
          
          <apex:pageblockButtons >
               <apex:commandButton value="Enviar Email" action="{!send}" onclick="if(!confirm('Estás seguro de enviarlo?')) return false;"/>
          </apex:pageblockButtons>
     
      </apex:pageBlock> 
  </apex:form>
</apex:page>
***Controller***
public class ControllerEnviaEmailInscripciones{

     public String Personalizaremail {get; set;}
     public Boolean thePanel         {get; set;}
     public String asunto            {get; set;}
     public String texto             {get; set;}
    
     public Attachment attachment {
        get {
            if (attachment == null)
                attachment = new Attachment();
            return attachment;
        }
        set;
     }
        
    public class ModelClass {
        public Inscripcion__c std  {get; set;}
        public Boolean flag        {get; set;}
    
    ModelClass(Inscripcion__c std) {
            this.std = std;
         // this.flag = true;
         }
     } 

    public List<ModelClass> models {get; set;}

    public ControllerEnviaEmailInscripciones() {
       Personalizaremail ='Email personalizado';
       String IdCapacitacion = System.currentPageReference().getParameters().get('id');
       models = new List<ModelClass>();
       for (Inscripcion__c c : [SELECT Id, Capacitacion__c, Estado__c, Name, NumeroInscripcion__c, Contacto__r.Name, CorreoElectronico__c, Cliente__r.Name 
                                FROM Inscripcion__c WHERE Capacitacion__c =:IdCapacitacion AND Contacto__r.email != NULL order by name limit 100]) {
            models.add(new ModelClass(c));
        }
     }
  
   public void click(){
       if (Personalizaremail == 'Email personalizado'){
           Personalizaremail ='Ocultar sección';
           thePanel = true;
       } else if (Personalizaremail == 'Ocultar sección') {
           Personalizaremail ='Email personalizado';
           thePanel = false;
       }
    }
    
    public PageReference send() {
 if (Personalizaremail == 'Email personalizado')  {        
     try {  
          EmailTemplate template = [ Select Id from EmailTemplate where developername = 'Capacitacion'];
         
            List<Messaging.Emailfileattachment> fileAttachments = new List<Messaging.Emailfileattachment>();
            Messaging.Emailfileattachment attachmentForMail = new Messaging.Emailfileattachment();
            attachmentForMail.setFileName(attachment.name); 
            attachmentForMail.setBody(attachment.Body);
            fileAttachments.add(attachmentForMail);
    
              Messaging.SingleEmailMessage[] messages = new Messaging.SingleEmailMessage[] {};
                for (ModelClass m : models) {
                    if (m.flag) {
                        Messaging.SingleEmailMessage message = new Messaging.SingleEmailMessage();
                        message.setTargetObjectId(m.Std.Contacto__r.Id);
                        message.setTemplateId(template.Id);
                           if(attachment.name !=NULL && attachment.Body !=NULL) {//verificamos que hay un archivo adjunto
                              message.setFileAttachments(fileAttachments);
                          } 
                        messages.add(message);
                     }
                  }
             Messaging.sendEmail(messages, true );
            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.CONFIRM,'Email enviado correctamente.'));
        } Catch(Exception e){
                e.getMessage();
            } finally {
             attachment.Body = null;
            } 
   } else if (Personalizaremail == 'Ocultar sección'){   //termina if (Personalizaremail == 'Ocultar sección')
         try {  
         
            List<Messaging.Emailfileattachment> fileAttachments = new List<Messaging.Emailfileattachment>();
            Messaging.Emailfileattachment attachmentForMail = new Messaging.Emailfileattachment();
            attachmentForMail.setFileName(attachment.name); 
            attachmentForMail.setBody(attachment.Body);
            fileAttachments.add(attachmentForMail);
    
              Messaging.SingleEmailMessage[] messages = new Messaging.SingleEmailMessage[] {};
                for (ModelClass m : models) {
                    if (m.flag) {
                        Messaging.SingleEmailMessage message = new Messaging.SingleEmailMessage();
                        message.setTargetObjectId(m.Std.Contacto__r.Id);
                        message.setSubject(asunto);
                        message.setPlainTextBody(texto);
                          if(attachment.name !=NULL && attachment.Body !=NULL) {
                              message.setFileAttachments(fileAttachments);
                          } 
                        messages.add(message);
                     }
                  }
             Messaging.sendEmail(messages, true );
            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.CONFIRM,'Email enviado correctamente.'));
        } Catch(Exception e){
                e.getMessage();
            } finally {
             attachment.Body = null;
            } 
     }
    return null;  
   } 
   
}

***test class****
 
private class Test_ControllerEnviaEmailInscripciones {
  
    @isTest static void enviaEmail(){
        
     Account a = New Account();
        a.Name ='Alfredo';
        a.NombreComercial__c ='Alberto';
        a.GeneroCapital__c ='Hombre';
        insert (a);
        
     List<Contact> contactList = new List<Contact>();
        contactList.add(Util.createContact(a.Id, 'test contact2', 'email1@test.com', false));
        contactList.add(Util.createContact(a.Id, 'test contact2', 'email2@test.com', false));
        insert contactList;
     
  Test.startTest();
        
     Capacitacion__c cap = New Capacitacion__c();
        cap.Name ='Multple capacitacion';
        cap.TipoCapacitacion__c='Programa';
        cap.ClasificacionFormacion__c='Principiante';
        cap.AreaPromueveCurso__c='CACEX';
        cap.LugarImparte__c='Procomer';
        cap.FechaInicial__c= System.today() + 4;
        insert(cap);
       
      Inscripcion__c insc = New Inscripcion__c();
        insc.Capacitacion__c = cap.Id;
        insc.Cliente__c=a.Id;
        insc.Contacto__c=contactList[0].Id;
        insc.Name =contactList[0].Name;
        insc.CorreoElectronico__c=contactList[0].Email;
        insc.Estado__c='Asiste';
        insc.RegistroAsistencia__c= System.today()+ 1;
        insc.FechaConfirmacion__c=  System.today() + 2;
        insc.NumeroInscripcion__c= '1';
        insert(insc);
        
        Attachment attach=new Attachment();   	
    	attach.Name='Unit Test Attachment';
    	Blob bodyBlob=Blob.valueOf('Unit Test Attachment Body');
    	attach.body=bodyBlob;
        attach.parentId=cap.id;
        insert attach;
       
        PageReference pref = Page.EnviaEmailInscripciones;
        pref.getParameters().put('id', cap.id);
        Test.setCurrentPage(pref);
        
        ControllerEnviaEmailInscripciones envEmail = New ControllerEnviaEmailInscripciones();
        envEmail.texto ='test envía';
        envEmail.asunto='test asunto';
          pref = envEmail.send();
       
        envEmail.click();
 
        Test.stopTest();    
    }
   
    
    
    /***********************************test 2 - Parte seccion oculta *************************************************/

    
     @isTest static void enviaEmail2(){
        
     Account a = New Account();
        a.Name ='Alfredo';
        a.NombreComercial__c ='Alberto';
        a.GeneroCapital__c ='Hombre';
        insert (a);
        
     List<Contact> contactList = new List<Contact>();
        contactList.add(Util.createContact(a.Id, 'test contact1', 'email1@test.com', false));
        contactList.add(Util.createContact(a.Id, 'test contact2', 'email2@test.com', false));
        insert contactList;
     
  Test.startTest();
        
     Capacitacion__c cap = New Capacitacion__c();
        cap.Name ='Multple capacitacion';
        cap.TipoCapacitacion__c='Programa';
        cap.ClasificacionFormacion__c='Principiante';
        cap.AreaPromueveCurso__c='CACEX';
        cap.LugarImparte__c='Procomer';
        cap.FechaInicial__c= System.today() + 4;
        insert(cap);
       
        Inscripcion__c insc = New Inscripcion__c();
        insc.Capacitacion__c = cap.Id;
        insc.Cliente__c=a.Id;
        insc.Contacto__c=contactList[0].Id;
        insc.Name =contactList[0].Name;
        insc.CorreoElectronico__c=contactList[0].Email;
        insc.Estado__c='Asiste';
        insc.RegistroAsistencia__c= System.today()+ 1;
        insc.FechaConfirmacion__c=  System.today() + 2;
        insc.NumeroInscripcion__c= '1';
        insert (insc); 
       
       Inscripcion__c insc2 = New Inscripcion__c();
        insc2.Capacitacion__c = cap.Id;
        insc2.Cliente__c=a.Id;
        insc2.Contacto__c=contactList[1].Id;
        insc2.Name =contactList[1].Name;
        insc2.CorreoElectronico__c=contactList[1].Email;
        insc2.Estado__c='Asiste';
        insc2.RegistroAsistencia__c= System.today()+ 1;
        insc2.FechaConfirmacion__c=  System.today() + 2;
        insc2.NumeroInscripcion__c= '2';
        insert (insc2); 
         
        Attachment attach=new Attachment();   	
    	attach.Name='Prueba Adjunto';
    	Blob bodyBlob=Blob.valueOf('Cuerpo del Archivo');
    	attach.body=bodyBlob;
        attach.parentId=cap.id;
        insert attach;
        
       // System.currentPageReference().getParameters().put('id', cap.Id);
        PageReference pref = Page.EnviaEmailInscripciones;
        pref.getParameters().put('id', cap.id);
        Test.setCurrentPage(pref);
       
        ControllerEnviaEmailInscripciones envEmail = New ControllerEnviaEmailInscripciones();
         
        envEmail.texto ='test envía';
        envEmail.asunto='test asunto';
        envEmail.Personalizaremail = 'Ocultar sección';
       
       pref = envEmail.send();
        envEmail.click();

        Test.stopTest();    
    }
}

​​​​​​​
Hello Guys,

I am new to documentation. I got asked to document the existing class, batch jobs, triggers for migration perpose. could you guys give some idea where to start and how we can identify the class and related objects? it would be great help if you guys could provide some guidance on this.

thanks

Hey guys,

 

Does anyone have good examples of documentation they've written for custom Apex/VF? I basically have a handful of new classes, and I want to document what they do, testing procedures, what they affect, etc.

 

Any examples out there would be great!

 

Cheers,

Jon

  • September 13, 2012
  • Like
  • 0

Hi All,

I created one Apex documentation tool just like javadoc. Please share your feedbacks on that.

 

http://www.aslambari.com/apexdoc.html

 

Blog:-

http://techsahre.blogspot.com/2011/01/apexdoc-salesforce-code-documentation.html

 

Thanks

Aslam Bari

  • January 27, 2011
  • Like
  • 0

Is anyone doing this successfully?  We're at a point where I'd like to migrate from just using regular code comments to using full blown javadoc-accessible documentation, to make it easier and more appealing for our devs to reuse code.

 

Can anyone provide any examples of generating javadoc html from the .cls files stored by Eclipse?

Is there any tool available through which we can review Apex code?