• Bryan Telford
  • NEWBIE
  • 100 Points
  • Member since 2013

  • Chatter
    Feed
  • 1
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 15
    Questions
  • 27
    Replies
Hi,

I have created a Visualforce Page to be able to upload attachment in Salesforce for X-Author application since Salesforce doesn't allow anymore to create any attachments in attachment object.
Everything is working as expected. I just need help to get full code coverage.
Only 47% with the test cIass I wrote. Could you tell me why I am not able to cover it all and what is wrong?
 
//VF Page :
<apex:page standardController="Apttus_XApps__Application__c" extensions="AttachmentUploadController">
  <apex:form >
      <apex:pageBlock title="Upload Attachment">
            <apex:inputFile style="width:100%" id="fileToUpload" value="{!fileBody}" filename="{!fileName}" />
            <apex:commandButton value="Upload Attachment" action="{!UploadFile}"/>
       </apex:pageBlock>
  </apex:form>
</apex:page>

//Controller :
public with Sharing class AttachmentUploadController {

    public Id recId
    {    get;set;    }
    
    public AttachmentUploadController(ApexPages.StandardController ctlr)
    {
       recId = ApexPages.CurrentPage().getParameters().get('Id');      
    }
    
    public string fileName 
    {    get;set;    }
    
    public Blob fileBody 
    {    get;set;    }
  
    public PageReference UploadFile()
    {    
        PageReference pr;
        if(fileBody != null && fileName != null)
        {
          Attachment myAttachment  = new Attachment();
          myAttachment.Body = fileBody;
          myAttachment.Name = fileName;
          myAttachment.ParentId = recId;
          insert myAttachment;
            
           pr = new PageReference('/' + myAttachment.Id);
           pr.setRedirect(true);
           return pr;
        }
        return null;
    }    
}


// Test method:
@isTest
public class AttachmentUploadController_Test{

    static testMethod void testCase1() {        
        Id recID;    
    PageReference pr;
        String filename = 'Att1';
        Blob Body = Blob.valueof('Unit Test Attachment Body');

        Apttus_XApps__Application__c objApp = New Apttus_XApps__Application__c();
        objApp.Name = 'Test Upload Attachment';
        objApp.Apttus_XApps__Activated__c = True;
        objApp.Apttus_XApps__UniqueId__c ='123ADCDEFG';
        insert objApp;
        
        recID = objApp.Id;      
        
        AttachmentUploadController controller=new AttachmentUploadController(new ApexPages.StandardController(objApp));        
        
        Attachment myAttachment =New attachment();
        myAttachment.name =filename;
        myAttachment.Body = Body;
        myAttachment.ParentId = recID;
        controller.UploadFile();        

    }      
          
}
In the Developer console I see that this lines of the controller are not covered :

- public string fileName

-   Attachment myAttachment  = new Attachment();
    myAttachment.Body = fileBody;
    myAttachment.Name = fileName;
    myAttachment.ParentId = recId;
    insert myAttachment;
                        
           pr = new PageReference('/' + myAttachment.Id);
           pr.setRedirect(true);
           return pr;

Thank you.
Ludivine
I have the following Apex class and VF page.  Based on the selection of the tite, the corresponding role should display. I am using the actionSupport to pass the selected value onchange event, and assign the value to selectedTitle. But the selectedTitle is null everytime. Any ideas?

Apex class:
public class selectListController
{
    public String title { get; set; }
    public String role { get; set; }    
    public String selectedTitle { get; set; }        
    public List<selectOption> titleList { get; set; }
    public List<selectOption> roleList { get; set; }
    
    public selectListController()
    {
        titleList = new List<selectOption>();
        titleList.add(new SelectOption('', '--None--'));
        for (TitleRoleAssociation__c title : [Select Title_Definition__r.Name from TitleRoleAssociation__c]) {
            titleList.add(new selectOption(title.Title_Definition__r.Id, title.Title_Definition__r.Name));
        }
    }
    
    public PageReference getRoles(){
        roleList = new List<selectOption>();
        roleList.add(new SelectOption('', '--None--'));
        System.debug('Selected title: ' + selectedTitle);
        for (TitleRoleAssociation__c role : [Select Role_Definition__r.Name from TitleRoleAssociation__c where Title_Definition__r.Name = :selectedTitle]) {
            roleList.add(new selectOption(role.Role_Definition__r.Id, role.Role_Definition__r.Name));
        }
    
        return null;
    }
    
}

VF page:
<apex:page controller="selectListController">
    <apex:form>
        <apex:selectList value="{!title}" multiselect="false" size="1">
            <apex:selectOptions value="{!titleList}" />
            <apex:actionSupport event="onchange" action="{!getRoles}" reRender="role" status="status">                         
               <apex:param name="selectedTitle" value="{!title}" assignTo="{!selectedTitle}"/>
            </apex:actionSupport>            
        </apex:selectList>

        <apex:outputPanel id="role">
        <apex:selectList value="{!role}" multiselect="false" size="1">
            <apex:selectOptions value="{!roleList}" />
        </apex:selectList>        
        </apex:outputPanel>
    </apex:form>
</apex:page>
 
I have the following Apex class and test class that is only getting 15/21 lines covered. The part that is not covered is in bold below. Any ideas how I can get the setter covered in this Apex?

public class changeControlExtension {
    public Infrastructure_Change_Control__c cc {get;set;}
     
    public changeControlExtension(ApexPages.StandardController stdCtrl) {
        cc = (Infrastructure_Change_Control__c)stdCtrl.getRecord();
    }
     
    //get the multi-select pick list values
    public List<SelectOption> getMSPicklist {
        get {
            List<SelectOption> options = new List<SelectOption>();
            for(Schema.PicklistEntry obj : Infrastructure_Change_Control__c.Department_Approvals__c.getDescribe().getPicklistValues()) {
                options.add(new SelectOption(obj.getValue(), obj.getLabel()));
            }
            return options;
        }  
        set;
    }
     
    //get and set the multi-select pick list as checkboxes
    public String[] MSItems {
        get {
            List<String> selected = new List<String>();
            List<SelectOption> options = this.getMSPicklist;
            for(SelectOption obj : options) {
                if (this.cc.Department_Approvals__c !=null && this.cc.Department_Approvals__c.contains(obj.getValue()))
                    selected.add(obj.getValue());
            }
            return selected;
        }
        set {
            String selectedCheckBox = '';
            for(String s : value) {
                if (selectedCheckBox == '')
                    selectedCheckBox += s;
                else selectedCheckBox += ';' + s;
            }
            cc.Department_Approvals__c = selectedCheckBox;

        }
    }
}

Test Class
@isTest
public class changeControlExtension_Test {

    private static testmethod void changeControl() {
     
     Case cas = new Case(Subject = 'Testcase');
     insert cas;
     
     Infrastructure_Change_Control__c cc = new Infrastructure_Change_Control__c(Name = 'Test Change', Related_Case__c = cas.id);
     insert cc;
             
     ApexPages.StandardController controller = new ApexPages.StandardController(cc);
     changeControlExtension extension = new changeControlExtension(controller);
     
     Test.startTest();
     List<SelectOption> options = extension.getMSPicklist;
     cc.Department_Approvals__c = options.get(0).getValue();
     String[] items = extension.MSItems;
     Test.stopTest();
     
     System.assertNotEquals(options.get(0).getValue(), null);
     System.assertNotEquals(items, null);
        
    }

}
I am creating an applicant tracking system. I have an input page where the user can provide the applicant details.

The parent object is an "applicant" and there are some child objects. One of those child objects is "equipment". On the input page, I need up to 5 rows pre-populated with different data for the equipment object. Each row will be one record. The problem is the records aren't created yet, but I want to pre-fill values because most of the time it's not going to change. The user should be able to remove 1 or more rows. When the user submits the rows still on the page will be saved as child records.

Is this feasible? I can write a for loop to insert multiple child objects, Does anyone have any tips to pre-populate the child rows? Below is a screen shot. Each row will correspond to one child record that would be created when the user submits the page.
User-added image
I have to parse a JSON response and either insert or update records, depending on finding a matching userId in the JSON for existing records in Salesforce. I have setup a wrapper class using https://json2apex.herokuapp.com/ to help with deserializing the JSON.

My code where I deserialize the JSON:
List<encompassRESTUsers> users = (List<encompassRESTUsers>)JSON.deserialize(JSONResponse, List<encompassRESTUsers>.class);   

I then create a list of the current records in the database, so that I have something to loop through and compare with the list I got from the JSON.
Persona_Audit__c[] currentUserList = [Select User_Id__c, id from Persona_Audit__c];

Here is where I am stuck. I know that I need to iterate through the deserialized JSON. Then I need to find out if the userId in the JSON already exists in a record. If it does, then I need to update that record. If not, then I need to create a new record. I'm seeing something like this but I don't know what to put in the for loops.

for (encompassRESTUsers u: users) {
            
   }
          
for (Persona_Audit__c theList : currentUserList) {

 }

Below is an example of the JSON.
[{
        "userId": "jsmith",
        "firstName": "Smith",
        "lastName": "Joseph",
        "workingFolder": "2 - Originated Applications",
        "subordinateLoanAccess": "ReadOnly",
        "userIndicators": [
            "Locked",
            "Disabled"
        ],
        "peerLoanAccess": "Disabled",
        "personalStatusOnline": true
    },
    {
        "userId": "zmoore",
        "firstName": "Zachary",
        "lastName": "Moore",
        "workingFolder": "1 - Leads-Prospects",
        "subordinateLoanAccess": "ReadOnly",
        "userIndicators": [
            "Locked",
            "Disabled"
        ],
        "peerLoanAccess": "Disabled",
        "personalStatusOnline": true
    }
]


 
I have the following Apex class and test clas.

public class passwordReset
{
 
    Decimal minimumPasswordLength;
    Decimal minimumPINNumberLength;    
    
    public String selectedOption { get; set; }
    
    String requestId = ApexPages.currentPage().getParameters().get('request_id');
    
    Encompass_Password_Service__c settings = Encompass_Password_Service__c.getOrgDefaults();   
    String currentUserContactdId = [select User.Contact.Id from User where id = :UserInfo.getUserId()].Contact.Id;
    //String currentUserContactdId = '0030R00000MNIJS';
    
    Decimal pinExpiration = settings.PIN_Number_Expiration_Minutes__c;
    Decimal maxPasswordResets = settings.Maximum_Resets_Per_Day__c;
    Decimal maxAccountUnlocks = settings.Maximum_Unlocks_Per_Day__c;    
    //Integer additionalMinutes = pinExpiration.intValue();
         
 
    
    public void requestPin()
    {
      String requestGuid = Random.generateGuid();
      //Generate PIN number
      
      integer numberOfResets= [Select count() from Encompass_Password_Reset__c where CreatedDate = TODAY and User_Selected_Option__c = 'Reset'];
      integer numberOfUnlocks= [Select count() from Encompass_Password_Reset__c where CreatedDate = TODAY and User_Selected_Option__c = 'Unlock'];            
      
      System.debug('selected option: ' + this.selectedOption);        
      if(this.selectedOption == 'Reset' && numberOfUnlocks < 5){
          //insert event
          Encompass_Password_Reset__c resetEvent = new Encompass_Password_Reset__c(PIN_Number__c = '1234', 
          Requested_Date_Time__c = System.Now(), 
          Employee__c = currentUserContactdId, 
          Request_Guid__c = requestGuid,
          Username__c = 'test.lo',
          User_Selected_Option__c = 'Reset',
          PIN_Number_Expiration__c = System.Now().addMinutes(60));
          insert resetEvent;
          ApexPages.addmessage(new ApexPages.message(ApexPages.severity.CONFIRM,'A PIN was sent to your email.The PIN will expire in 60 minutes.')); 
      }

      else if(this.selectedOption == null) {
         ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR,'Please select an option.')); 
      }
      
   
    }    
        
}

TEST CLASS
@isTest
public class passwordResetTest {

    private static testmethod void requestPinForPasswordReset() {

    Test.setCurrentPage(new PageReference('request_pin'));  
    
    Encompass_Password_Reset__c reset = createRequest(requestType); insert reset;
    encompassPasswordService controller = new encompassPasswordService();
    
    Test.startTest();
    controller.requestPin();
    Test.stopTest();
    
          
    List<ApexPages.Message> msgList = ApexPages.getMessages();
        
    for(ApexPages.Message msg :  ApexPages.getMessages()) {
        System.assertEquals('A PIN was sent to your email.The PIN will expire in 60 minutes.', msg.getSummary());
        System.assertEquals(ApexPages.Severity.CONFIRM, msg.getSeverity()); 
    }
           
    }
    
    private static Encompass_Password_Reset__c createRequest(String requestType) {
        
        Account acc = new Account(Name = 'Sample Account'); insert acc;
        Contact con = new Contact(LastName = 'Smith', AccountId = acc.id); insert con; 
        
        TestHelper.ObjectMother mo = new TestHelper.ObjectMother();
        User usr = mo.createUser(con.id, con.Email = 'test345@test.com', acc.Name); insert usr;
        
        //Integer additionalMinutes = settings.PIN_Number_Expiration_Minutes__c.intValue();
        
        String requestGuid = Random.generateGuid();
        String selectedOption = requestType;
        
        Encompass_Password_Reset__c event = new Encompass_Password_Reset__c(
            Request_Guid__c = requestGuid, 
            PIN_Number__c = '477405',
            User_Selected_Option__c = requestType, 
            Requested_Date_Time__c = System.Now(),
            Username__c = 'lo.test',
            Employee__c = usr.Contact.Id,
            PIN_Number_Expiration__c = System.Now().addMinutes(60));
            
            System.debug('request type: ' + event.User_Selected_Option__c);
      
            return event;
    }

}

The test fails with this message.
System.AssertException: Assertion Failed: Expected: A PIN was sent to your email.The PIN will expire in 60 minutes., Actual: Please select an option.

When I look at the debug log, the "selected option" is null, therefore the test returns the message as specified by this condition in the controller:  
    else if(this.selectedOption == null) 

How can I modify the test class to recognize the selected option that is set in the VF page?
I have the following class which fails to get code coverage on lines in bold. I have searched through the forums and can't determine how to get those particular lines covered. 

public without sharing class projectWizardController {

Project__c project;

   public Project__c getProject() {
      if(project == null) project = new Project__c();
      project.Plan__c = ApexPages.currentPage().getParameters().get('planId');
      project.Status__c = 'New';
      return project;
   }    
   
   public PageReference step1() {      
      return Page.new_project_p1;
   }
   
   public PageReference step2() {      
      return Page.new_project_p2;
   }
   
   public PageReference step3() {      
      return Page.new_project_p3;
   }
             
   public PageReference submit() {

      try {     
          //if(project.get('Id') == null) 
          project.Status__c = 'Submitted';
          project.Submitted__c = Date.Today();
          insert project;
          PageReference projectPage = new PageReference('/apex/manage_project?id=' + project.id + '&planId='+          ApexPages.currentPage().getParameters().get('planId'));
          projectPage.setRedirect(true);         
          return projectPage;

    
        }
      catch (Exception e) {apexpages.addmessages(e);}return null;

     }         
}

The test class is below.
@isTest
public class projectWizardControllerTest {
  private static testmethod void testSubmittedProject() {
 
    projectWizardController controller = new projectWizardController(); 

    //ARRANGE    
    Plan__c plan = new Plan__c();insert plan;
    Project__c project = controller.getProject();
    project.Plan__c = plan.id;
    project.Status__c = 'Submitted';
    insert project;
    
    //ACT
    Test.startTest();
        controller.step1();
        controller.step2();
        controller.step3();                
        controller.submit();           
        PageReference pageRef = Page.manage_project;
        Test.setCurrentPage(pageRef);
        ApexPages.currentPage().getParameters().put('planid',plan.id);
        ApexPages.currentPage().getParameters().put('id',project.id);
        ApexPages.currentPage().setRedirect(true);        
    Test.stopTest();        
    //ASSERT
    System.assertEquals(project.Status__c, 'Submitted');         
}
}
I have the following Apex class that is only getting 57% code coverage.  Test class below as well. I feel like there is something simple that I'm missing. Any help would be appreciated!

public class taskController{

    public Project_Task__c task{get;set;}
    public List<Project_Task_Assignment__c> assignment{get;set;}
    public taskController(){
        task = new Project_Task__c();
        assignment = new List<Project_Task_Assignment__c>();
        task.Project__c = ApexPages.currentPage().getParameters().get('Id');
     
    }
    public void AddRow(){
        assignment.add(new Project_Task_Assignment__c());
    
    }
    public PageReference save(){

     try{
            insert task;
            List<Project_Task_Assignment__c> taskAssignment = new List<Project_Task_Assignment__c>();
            for(Project_Task_Assignment__c c : assignment){
                c.Project_Task__c = task.id;
                taskAssignment.add(c);
    
            }

            if(assignment != null){
                insert taskAssignment;
           }
           
            PageReference taskPage = new PageReference('/apex/manage_task?id=' + task.id);
        taskPage.setRedirect(true);
        return taskPage;
      } 
      
     catch (Exception e) {apexpages.addmessages(e);}return null;        
      
  }  
    
}

*****Test Class*****
@isTest
    public class taskControllerTest{
         private static testMethod void saveTask() {
        
         Account acc = new Account(Name = 'Sample Account'); insert acc;
         Contact con = new Contact(LastName = 'Smith', AccountId = acc.id); insert con;    
         Plan__c plan = new Plan__c(Name = 'Test'); insert plan;
         Project__c project = new Project__c(Name = 'Test', Plan__c = plan.id); insert project;
         
    
            
    
         Test.startTest();
         
         PageReference pageRef = Page.AccountContact;
         
         Project_Task__c task = new Project_Task__c(Project__c = project.id, Name = 'Test Task'); 
         insert task;
         Project_Task_Assignment__c assignment = new Project_Task_Assignment__c(Project_Task__c = task.id, Contact__c = con.id);
         insert assignment;
         Test.setCurrentPage(pageRef);
         taskController controller = new taskController();
         controller.addRow();       

         controller.save();
         pageRef.getParameters().put('id',task.id);   

         Test.stopTest();        
         
         System.assertNotEquals(task.Name, null);
         System.assertNotEquals(assignment, null);         
    
   } 
             
}
I am trying to get code coverage for the following controller. This is based on the calendar project found at https://github.com/sxg133/VFCalendar

/**
*   Controller for calendar component demo
*
*   @author Sahil Grover 
*/
public with sharing class CalendarController implements CalendarItemRetriever {

    public CalendarHandler Cal {get; private set;}
    public CalendarParameters CalParams {get; private set;}

    public CalendarController() {
        CalParams = new CalendarParameters();
        CalParams.SelectedView = CalendarParameters.CalendarView.MONTH;
        Cal = new CalendarHandler(this);
    }

    /**
    *   Get calendar items in a date range
    *
    *   @param  startDate   The start date (inclusive) to retrieve calendar items for
    *   @param  endDate     The end date (inclusive) to retrieve calendar items for
    *
    *   @return A list of CalendarItem objects
    */
    public List<CalendarItem> getCalendarItems(Date startDate, Date endDate) {
        List<CalendarItem> calendarItems = new List<CalendarItem>();
        // custom events
        List<Calendar_Event__c> customEvents = new List<Calendar_Event__c>([
            SELECT Id, Name, Description__c, Start_Date_Time__c,
                End_Date_Time__c, Is_All_Day__c, Link__c, Trainer__c
            FROM Calendar_Event__c
            WHERE Start_Date_Time__c >= :startDate
                AND End_Date_Time__c <= :endDate
            ]);
        for (Calendar_Event__c e : customEvents) {
            CalendarItem calItem = createCalendarItem(e);
            calendarItems.add(calItem);
        }

        return calendarItems;
    }

    private CalendarItem createCalendarItem(Calendar_Event__c e) {
        CalendarItem calItem = new CalendarItem(e.Id);
        calItem.Name = e.Name;
        calItem.Description = e.Description__c;
        calItem.StartDateTime = e.Start_Date_Time__c;
        calItem.EndDateTime = e.End_Date_Time__c;
        calItem.IsAllDay = e.Is_All_Day__c;
        calItem.Link = e.Link__c;
        calItem.Trainer = e.Trainer__c;
        calItem.CssClass = 'custom-event';
        return calItem;
    }
   
}

Test class
@isTest
private class CalendarControllerTest{

      private static testMethod void CalendarTest() {
             
        Test.startTest();
        CalendarController calendar = new CalendarController();
  
        Test.stopTest();

       } 
       
    }

It gets covered 50% simply by calling CalendarController calendar = new CalendarController(); in the Test.startTest() method.

I know this is probably a somewhat simple apex test question, but I cannot figure out how to get the rest of the code covered.

Any help is appreciated!
I have the following code.

 webService static List<Attachment> getSearchedFiles(String query) {
       String[] searchKeys = query.split(' ');

    for (Integer i = 0; i < searchKeys.size(); i++) {
        searchKeys[i] = '%' + searchKeys[i] + '%';
    }
      system.debug(searchKeys);    
       List<Document_Folder__c> files = [
           select 
            id, 
            (
               select id, Name, Description, BodyLength, CreatedDate, CreatedBy.Name, LastModifiedDate, LastModifiedBy.Name, ParentId,         Parent.Name 
               from attachments 
               where Name LIKE :searchKeys order by Name
            ), 
           from Document_Folder__c
       ];

The debug log shows the correct value that I want.
11:51:47.0 (31583876)|USER_DEBUG|[40]|DEBUG|(%chat%, %talk%)

But no query results are returned. Any thoughts? 

Thanks!
 
Can anyone let me know where I'm going wrong?  Below is my Apex class. I get the following error when the VF page tries to call it. I'm sure it's because it can't convert String to a List, but I have no idea how to fix it. The email examples given by Salesforce always have a hardcoded email address.Thank you for any help!           

common.apex.runtime.impl.ExecutionException: Invalid conversion from runtime type String to List<String>

public with sharing class AttachmentUploadController

{
    public String EmailSubject { get;  set; }
    public String EmailBody { get;  set; }
    public String ToEmails{ get;  set; }
    
    public Attachment attachment 
    {
        get
        {
            if (attachment == null)
            attachment = new Attachment();
            return attachment;
        }
        set;
    }

    public PageReference sendEmail() 
    {
        String parentId = System.currentPagereference().getParameters().get('id');
        String[] ToAddresses = this.ToEmails.split(';');
        
        try
        {

            //Start: Send Email with Attachment
            Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();                    
                        
            mail.setToAddresses(ToAddresses);
            mail.setHTMLBody(this.EmailBody);
            mail.setSubject(this.EmailSubject);         

            //Set email file attachments
            List<Messaging.Emailfileattachment> fileAttachments = new List<Messaging.Emailfileattachment>();

            // Add to attachment file list
            Messaging.Emailfileattachment efa = new Messaging.Emailfileattachment();
            efa.setFileName(attachment.Name);
            efa.setBody(attachment.Body);
            fileAttachments.add(efa);

            //create attachment for object

            mail.setFileAttachments(fileAttachments);

            //Send email
            Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
            //END : Send Email with Attachment

            PageReference page = new PageReference('/' + parentId);
            return page;
        } 
        catch (DMLException e) 
        {
            ApexPages.addMessage(new ApexPages.message(ApexPages.severity.ERROR,'Email Not Sent'));
            return null;
        }
        finally
        {
            attachment = new Attachment(); 
        }
    }
  }
Hello! I'm trying to send an email through Apex. Can anyone help me understand why the following code results in this error?
SendEmail failed. First exception on row 0; first error: INVALID_EMAIL_ADDRESS, Email address is invalid: : [toAddresses, ]

Code is below
            Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();                           
            
            String sendEmailsTo = qcRequest.To_Emails__c;        
            String[] toAddresses = sendEmailsTo.split(';');
            System.debug('Emails: ' + toAddresses);
            
            mail.setToAddresses(toAddresses);
            
Thanks for any help you can provide!
I am trying to get code coverage for an exception in my test class. I have the following code in the class.

  public void requestReport() {   
     currentuser=[Select Id, Name, Email from User where Id=:userinfo.getuserId()];
        try 
            {     
                SQL_Report_Request__c request = new SQL_Report_Request__c (Request_Type__c = 'Branches Directory', Email__c = currentuser.Email);
                insert request;    
            }
                catch(DmlException ex){
                ApexPages.addMessages(ex);
           } 
    }

My unit test tries to insert an invalid email address, i.e. "test1234.com". The test passes with 90% but does not cover the following in my class.
  catch(DmlException ex){
                ApexPages.addMessages(ex);
}

Here is my unit test.
private static testMethod void testReportRequestWithDMLException() {
    branchesListController controller = new branchesListController();
       // ARRANGE
       List<SQL_Report_Request__c> request = new List<SQL_Report_Request__c> {
            new SQL_Report_Request__c(Request_Type__c = 'Branches', Email__c = 'test1234.com')
        };

       
       // ACT 

          try {
        controller.requestReport();
        insert request;
        }
        catch(DmlException ex) {
             //Assert Error Message

           System.assertNotEquals(ex, null);
     
        }
Assume I have the following section of xml. I need to parse each individual _CreditScore attribute for each BORROWER/_CREDIT_SCORE/_CREDIT_SCORE

<BORROWER BorrowerID="B11467282">
    <_CREDIT_SCORE> 
        <_CREDIT_SCORE _CreditScore="691" _ReportingAgency="Experian" /> 
        <_CREDIT_SCORE _CreditScore="695" _ReportingAgency="TransUnion" /> 
        <_CREDIT_SCORE _CreditScore="678" _ReportingAgency="Equifax" /> 
    </_CREDIT_SCORE> 
</BORROWER> 
<BORROWER BorrowerID="B11467439" 
    <_CREDIT_SCORE> 
        <_CREDIT_SCORE _CreditScore="685" _ReportingAgency="Experian" /> 
        <_CREDIT_SCORE _CreditScore="681" _ReportingAgency="TransUnion" /> 
        <_CREDIT_SCORE _CreditScore="684" _ReportingAgency="Equifax" /> 
    </_CREDIT_SCORE> 
</BORROWER>

Using the below code, I would have thought it would loop through both BORROWER elements and each /BORROWER/_CREDIT_SCORE/_CREDIT_SCORE section.

However, the result is that it only loops twice through the first /BORROWER/_CREDIT_SCORE/_CREDIT_SCORE, so I end up with the same value twice in my debug log.

Actual Result: 14:23:13.143 (1156222554)|USER_DEBUG|[179]|DEBUG|Experian: (691, 691)
Expected Result: 14:23:13.143 (1156222554)|USER_DEBUG|[179]|DEBUG|Experian: (691, 685)

Here is the parsing logic.

List<String> Experian = new List<String>();
List<String> Equifax = new List<String>();    
List<String> Transunion = new List<String>();        

for (Dom.XmlNode node : doc.getRootElement().getChildElement('_APPLICATION', null).getChildElement('BORROWER', null).getChildElement('_CREDIT_SCORE', null).getChildElements()) {
                 if(node.getAttributeValue('_ReportingAgency','')=='Experian')  {
                    Experian.add(node.getAttributeValue('_CreditScore', ''));
                    System.debug('Experian: ' + Experian);
                 }
                 if(node.getAttributeValue('_ReportingAgency','')=='Equifax') {
                    Equifax.add(node.getAttributeValue('_CreditScore', ''));
                    System.debug('Equifax: ' + Equifax);
                 }
                 if(node.getAttributeValue('_ReportingAgency','')=='TransUnion') {
                    Transunion.add(node.getAttributeValue('_CreditScore', ''));
                    System.debug('TransUnion: ' + Transunion);                    
                 }

For reference, here is the logic for inserting the data.
   for(Integer i = 1; i <= experian.size(); i++) {
                lockdata.put('NYLX_Experian_Score_'+i+'__c', integer.valueof(Experian.get(i-1)));
             } 
             
             for(Integer i = 1; i <= equifax.size(); i++) {
                lockdata.put('NYLX_Equifax_Score_'+i+'__c', integer.valueof(Equifax.get(i-1)));
             } 
             for(Integer i = 1; i <= transunion.size(); i++) {
                lockdata.put('NYLX_TransUnion_Score_'+i+'__c', integer.valueof(Transunion.get(i-1)));
             }

Thanks for any help!
I have the below FOR loop, which gets the attribute value of 'descript' and assigns it to the adjDescription variable. The incoming xml actually has 6 repeating child elements under PRICING_DETAILS, each with a different value in 'descript'.  Using the System.debug statement I am able to see each of the 'descript' values, so I know it's correctly iterating. However, I need to assign each value to a variable, so I can use them for inserting the data. 

 for (Dom.XmlNode node : doc.getRootElement().getChildElement('PRICING_DETAILS', null).getChildElements()){
                 if(node.getAttributeValue('descript','') != null) {
                    adjDescription = node.getAttributeValue('descript', '');
                    System.debug(adjDescription)
                   
                 }
    
             }

// Insert the data.
 NYLX_Lock_Data__c lockdata = new NYLX_Lock_Data__c(
     NYLX_Adjustment_Desc_1__c = adjDescription,
     NYLX_Adjustment_Desc_2__c = adjDescription
      );  
     insert lockdata; 

The above code for the insert is not working because it assigns the same adjDescrpition value for both. How do I increment the adjDescription variable in the FOR loop, so I that I am able to assign each one when I insert the data?  For reference here is the relevant part in the debug log showing each value from the loop.

12:58:35.12 (625245897)|USER_DEBUG|[194]|DEBUG|FCLS LTV / FICO Bump
12:58:35.12 (625303655)|USER_DEBUG|[194]|DEBUG|LTV Range: FICO >= 740
12:58:35.12 (625349569)|USER_DEBUG|[194]|DEBUG|Condo: LTV > 75%
12:58:35.12 (625394298)|USER_DEBUG|[194]|DEBUG|FCLS Regional Subsidy TX
12:58:35.12 (625438759)|USER_DEBUG|[194]|DEBUG|FCLS - Purchase Special
12:58:35.12 (625488311)|USER_DEBUG|[194]|DEBUG|SRP Adjuster

Thanks for any help!
Does anyone know how to use the XML DOM to parse repeating nodes of XML? For example, let's say I have the following section.
        <_CREDIT_SCORE>
                <_CREDIT_SCORE _CreditScore="668" _ReportingAgency="Experian"/>
                <_CREDIT_SCORE _CreditScore="658" _ReportingAgency="TransUnion"/>
                <_CREDIT_SCORE _CreditScore="660" _ReportingAgency="Equifax"/>
            </_CREDIT_SCORE>
I need to use the DOM to parse the first _CREDIT_SCORE element, then the second, and third. Ultimately, I need the get the values of the attributes inside each _CREDIT_SCORE node.

The Salesforce documentation provided doesn't seem to have a way to do this. For example, using getChildElement will always return the first element. I need to be able to read each _CREDIT_SCORE.  

I've been struggling with this for weeks. It seems like it should be a fairly easy task, but using the DOM provided by Salesforce, there doesn't seem to be a way to get to the subsequent nodes after the first. Perhaps I've missed something in my reading of the documentation, or perhaps there is another way altogether. 

Thanks for any help!
 
I have the following Apex class and VF page.  Based on the selection of the tite, the corresponding role should display. I am using the actionSupport to pass the selected value onchange event, and assign the value to selectedTitle. But the selectedTitle is null everytime. Any ideas?

Apex class:
public class selectListController
{
    public String title { get; set; }
    public String role { get; set; }    
    public String selectedTitle { get; set; }        
    public List<selectOption> titleList { get; set; }
    public List<selectOption> roleList { get; set; }
    
    public selectListController()
    {
        titleList = new List<selectOption>();
        titleList.add(new SelectOption('', '--None--'));
        for (TitleRoleAssociation__c title : [Select Title_Definition__r.Name from TitleRoleAssociation__c]) {
            titleList.add(new selectOption(title.Title_Definition__r.Id, title.Title_Definition__r.Name));
        }
    }
    
    public PageReference getRoles(){
        roleList = new List<selectOption>();
        roleList.add(new SelectOption('', '--None--'));
        System.debug('Selected title: ' + selectedTitle);
        for (TitleRoleAssociation__c role : [Select Role_Definition__r.Name from TitleRoleAssociation__c where Title_Definition__r.Name = :selectedTitle]) {
            roleList.add(new selectOption(role.Role_Definition__r.Id, role.Role_Definition__r.Name));
        }
    
        return null;
    }
    
}

VF page:
<apex:page controller="selectListController">
    <apex:form>
        <apex:selectList value="{!title}" multiselect="false" size="1">
            <apex:selectOptions value="{!titleList}" />
            <apex:actionSupport event="onchange" action="{!getRoles}" reRender="role" status="status">                         
               <apex:param name="selectedTitle" value="{!title}" assignTo="{!selectedTitle}"/>
            </apex:actionSupport>            
        </apex:selectList>

        <apex:outputPanel id="role">
        <apex:selectList value="{!role}" multiselect="false" size="1">
            <apex:selectOptions value="{!roleList}" />
        </apex:selectList>        
        </apex:outputPanel>
    </apex:form>
</apex:page>
 
I have the following Apex class and test class that is only getting 15/21 lines covered. The part that is not covered is in bold below. Any ideas how I can get the setter covered in this Apex?

public class changeControlExtension {
    public Infrastructure_Change_Control__c cc {get;set;}
     
    public changeControlExtension(ApexPages.StandardController stdCtrl) {
        cc = (Infrastructure_Change_Control__c)stdCtrl.getRecord();
    }
     
    //get the multi-select pick list values
    public List<SelectOption> getMSPicklist {
        get {
            List<SelectOption> options = new List<SelectOption>();
            for(Schema.PicklistEntry obj : Infrastructure_Change_Control__c.Department_Approvals__c.getDescribe().getPicklistValues()) {
                options.add(new SelectOption(obj.getValue(), obj.getLabel()));
            }
            return options;
        }  
        set;
    }
     
    //get and set the multi-select pick list as checkboxes
    public String[] MSItems {
        get {
            List<String> selected = new List<String>();
            List<SelectOption> options = this.getMSPicklist;
            for(SelectOption obj : options) {
                if (this.cc.Department_Approvals__c !=null && this.cc.Department_Approvals__c.contains(obj.getValue()))
                    selected.add(obj.getValue());
            }
            return selected;
        }
        set {
            String selectedCheckBox = '';
            for(String s : value) {
                if (selectedCheckBox == '')
                    selectedCheckBox += s;
                else selectedCheckBox += ';' + s;
            }
            cc.Department_Approvals__c = selectedCheckBox;

        }
    }
}

Test Class
@isTest
public class changeControlExtension_Test {

    private static testmethod void changeControl() {
     
     Case cas = new Case(Subject = 'Testcase');
     insert cas;
     
     Infrastructure_Change_Control__c cc = new Infrastructure_Change_Control__c(Name = 'Test Change', Related_Case__c = cas.id);
     insert cc;
             
     ApexPages.StandardController controller = new ApexPages.StandardController(cc);
     changeControlExtension extension = new changeControlExtension(controller);
     
     Test.startTest();
     List<SelectOption> options = extension.getMSPicklist;
     cc.Department_Approvals__c = options.get(0).getValue();
     String[] items = extension.MSItems;
     Test.stopTest();
     
     System.assertNotEquals(options.get(0).getValue(), null);
     System.assertNotEquals(items, null);
        
    }

}
I am creating an applicant tracking system. I have an input page where the user can provide the applicant details.

The parent object is an "applicant" and there are some child objects. One of those child objects is "equipment". On the input page, I need up to 5 rows pre-populated with different data for the equipment object. Each row will be one record. The problem is the records aren't created yet, but I want to pre-fill values because most of the time it's not going to change. The user should be able to remove 1 or more rows. When the user submits the rows still on the page will be saved as child records.

Is this feasible? I can write a for loop to insert multiple child objects, Does anyone have any tips to pre-populate the child rows? Below is a screen shot. Each row will correspond to one child record that would be created when the user submits the page.
User-added image
Hi,

I have created a Visualforce Page to be able to upload attachment in Salesforce for X-Author application since Salesforce doesn't allow anymore to create any attachments in attachment object.
Everything is working as expected. I just need help to get full code coverage.
Only 47% with the test cIass I wrote. Could you tell me why I am not able to cover it all and what is wrong?
 
//VF Page :
<apex:page standardController="Apttus_XApps__Application__c" extensions="AttachmentUploadController">
  <apex:form >
      <apex:pageBlock title="Upload Attachment">
            <apex:inputFile style="width:100%" id="fileToUpload" value="{!fileBody}" filename="{!fileName}" />
            <apex:commandButton value="Upload Attachment" action="{!UploadFile}"/>
       </apex:pageBlock>
  </apex:form>
</apex:page>

//Controller :
public with Sharing class AttachmentUploadController {

    public Id recId
    {    get;set;    }
    
    public AttachmentUploadController(ApexPages.StandardController ctlr)
    {
       recId = ApexPages.CurrentPage().getParameters().get('Id');      
    }
    
    public string fileName 
    {    get;set;    }
    
    public Blob fileBody 
    {    get;set;    }
  
    public PageReference UploadFile()
    {    
        PageReference pr;
        if(fileBody != null && fileName != null)
        {
          Attachment myAttachment  = new Attachment();
          myAttachment.Body = fileBody;
          myAttachment.Name = fileName;
          myAttachment.ParentId = recId;
          insert myAttachment;
            
           pr = new PageReference('/' + myAttachment.Id);
           pr.setRedirect(true);
           return pr;
        }
        return null;
    }    
}


// Test method:
@isTest
public class AttachmentUploadController_Test{

    static testMethod void testCase1() {        
        Id recID;    
    PageReference pr;
        String filename = 'Att1';
        Blob Body = Blob.valueof('Unit Test Attachment Body');

        Apttus_XApps__Application__c objApp = New Apttus_XApps__Application__c();
        objApp.Name = 'Test Upload Attachment';
        objApp.Apttus_XApps__Activated__c = True;
        objApp.Apttus_XApps__UniqueId__c ='123ADCDEFG';
        insert objApp;
        
        recID = objApp.Id;      
        
        AttachmentUploadController controller=new AttachmentUploadController(new ApexPages.StandardController(objApp));        
        
        Attachment myAttachment =New attachment();
        myAttachment.name =filename;
        myAttachment.Body = Body;
        myAttachment.ParentId = recID;
        controller.UploadFile();        

    }      
          
}
In the Developer console I see that this lines of the controller are not covered :

- public string fileName

-   Attachment myAttachment  = new Attachment();
    myAttachment.Body = fileBody;
    myAttachment.Name = fileName;
    myAttachment.ParentId = recId;
    insert myAttachment;
                        
           pr = new PageReference('/' + myAttachment.Id);
           pr.setRedirect(true);
           return pr;

Thank you.
Ludivine
I have to parse a JSON response and either insert or update records, depending on finding a matching userId in the JSON for existing records in Salesforce. I have setup a wrapper class using https://json2apex.herokuapp.com/ to help with deserializing the JSON.

My code where I deserialize the JSON:
List<encompassRESTUsers> users = (List<encompassRESTUsers>)JSON.deserialize(JSONResponse, List<encompassRESTUsers>.class);   

I then create a list of the current records in the database, so that I have something to loop through and compare with the list I got from the JSON.
Persona_Audit__c[] currentUserList = [Select User_Id__c, id from Persona_Audit__c];

Here is where I am stuck. I know that I need to iterate through the deserialized JSON. Then I need to find out if the userId in the JSON already exists in a record. If it does, then I need to update that record. If not, then I need to create a new record. I'm seeing something like this but I don't know what to put in the for loops.

for (encompassRESTUsers u: users) {
            
   }
          
for (Persona_Audit__c theList : currentUserList) {

 }

Below is an example of the JSON.
[{
        "userId": "jsmith",
        "firstName": "Smith",
        "lastName": "Joseph",
        "workingFolder": "2 - Originated Applications",
        "subordinateLoanAccess": "ReadOnly",
        "userIndicators": [
            "Locked",
            "Disabled"
        ],
        "peerLoanAccess": "Disabled",
        "personalStatusOnline": true
    },
    {
        "userId": "zmoore",
        "firstName": "Zachary",
        "lastName": "Moore",
        "workingFolder": "1 - Leads-Prospects",
        "subordinateLoanAccess": "ReadOnly",
        "userIndicators": [
            "Locked",
            "Disabled"
        ],
        "peerLoanAccess": "Disabled",
        "personalStatusOnline": true
    }
]


 
I have the following Apex class and test clas.

public class passwordReset
{
 
    Decimal minimumPasswordLength;
    Decimal minimumPINNumberLength;    
    
    public String selectedOption { get; set; }
    
    String requestId = ApexPages.currentPage().getParameters().get('request_id');
    
    Encompass_Password_Service__c settings = Encompass_Password_Service__c.getOrgDefaults();   
    String currentUserContactdId = [select User.Contact.Id from User where id = :UserInfo.getUserId()].Contact.Id;
    //String currentUserContactdId = '0030R00000MNIJS';
    
    Decimal pinExpiration = settings.PIN_Number_Expiration_Minutes__c;
    Decimal maxPasswordResets = settings.Maximum_Resets_Per_Day__c;
    Decimal maxAccountUnlocks = settings.Maximum_Unlocks_Per_Day__c;    
    //Integer additionalMinutes = pinExpiration.intValue();
         
 
    
    public void requestPin()
    {
      String requestGuid = Random.generateGuid();
      //Generate PIN number
      
      integer numberOfResets= [Select count() from Encompass_Password_Reset__c where CreatedDate = TODAY and User_Selected_Option__c = 'Reset'];
      integer numberOfUnlocks= [Select count() from Encompass_Password_Reset__c where CreatedDate = TODAY and User_Selected_Option__c = 'Unlock'];            
      
      System.debug('selected option: ' + this.selectedOption);        
      if(this.selectedOption == 'Reset' && numberOfUnlocks < 5){
          //insert event
          Encompass_Password_Reset__c resetEvent = new Encompass_Password_Reset__c(PIN_Number__c = '1234', 
          Requested_Date_Time__c = System.Now(), 
          Employee__c = currentUserContactdId, 
          Request_Guid__c = requestGuid,
          Username__c = 'test.lo',
          User_Selected_Option__c = 'Reset',
          PIN_Number_Expiration__c = System.Now().addMinutes(60));
          insert resetEvent;
          ApexPages.addmessage(new ApexPages.message(ApexPages.severity.CONFIRM,'A PIN was sent to your email.The PIN will expire in 60 minutes.')); 
      }

      else if(this.selectedOption == null) {
         ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR,'Please select an option.')); 
      }
      
   
    }    
        
}

TEST CLASS
@isTest
public class passwordResetTest {

    private static testmethod void requestPinForPasswordReset() {

    Test.setCurrentPage(new PageReference('request_pin'));  
    
    Encompass_Password_Reset__c reset = createRequest(requestType); insert reset;
    encompassPasswordService controller = new encompassPasswordService();
    
    Test.startTest();
    controller.requestPin();
    Test.stopTest();
    
          
    List<ApexPages.Message> msgList = ApexPages.getMessages();
        
    for(ApexPages.Message msg :  ApexPages.getMessages()) {
        System.assertEquals('A PIN was sent to your email.The PIN will expire in 60 minutes.', msg.getSummary());
        System.assertEquals(ApexPages.Severity.CONFIRM, msg.getSeverity()); 
    }
           
    }
    
    private static Encompass_Password_Reset__c createRequest(String requestType) {
        
        Account acc = new Account(Name = 'Sample Account'); insert acc;
        Contact con = new Contact(LastName = 'Smith', AccountId = acc.id); insert con; 
        
        TestHelper.ObjectMother mo = new TestHelper.ObjectMother();
        User usr = mo.createUser(con.id, con.Email = 'test345@test.com', acc.Name); insert usr;
        
        //Integer additionalMinutes = settings.PIN_Number_Expiration_Minutes__c.intValue();
        
        String requestGuid = Random.generateGuid();
        String selectedOption = requestType;
        
        Encompass_Password_Reset__c event = new Encompass_Password_Reset__c(
            Request_Guid__c = requestGuid, 
            PIN_Number__c = '477405',
            User_Selected_Option__c = requestType, 
            Requested_Date_Time__c = System.Now(),
            Username__c = 'lo.test',
            Employee__c = usr.Contact.Id,
            PIN_Number_Expiration__c = System.Now().addMinutes(60));
            
            System.debug('request type: ' + event.User_Selected_Option__c);
      
            return event;
    }

}

The test fails with this message.
System.AssertException: Assertion Failed: Expected: A PIN was sent to your email.The PIN will expire in 60 minutes., Actual: Please select an option.

When I look at the debug log, the "selected option" is null, therefore the test returns the message as specified by this condition in the controller:  
    else if(this.selectedOption == null) 

How can I modify the test class to recognize the selected option that is set in the VF page?
I have the following class which fails to get code coverage on lines in bold. I have searched through the forums and can't determine how to get those particular lines covered. 

public without sharing class projectWizardController {

Project__c project;

   public Project__c getProject() {
      if(project == null) project = new Project__c();
      project.Plan__c = ApexPages.currentPage().getParameters().get('planId');
      project.Status__c = 'New';
      return project;
   }    
   
   public PageReference step1() {      
      return Page.new_project_p1;
   }
   
   public PageReference step2() {      
      return Page.new_project_p2;
   }
   
   public PageReference step3() {      
      return Page.new_project_p3;
   }
             
   public PageReference submit() {

      try {     
          //if(project.get('Id') == null) 
          project.Status__c = 'Submitted';
          project.Submitted__c = Date.Today();
          insert project;
          PageReference projectPage = new PageReference('/apex/manage_project?id=' + project.id + '&planId='+          ApexPages.currentPage().getParameters().get('planId'));
          projectPage.setRedirect(true);         
          return projectPage;

    
        }
      catch (Exception e) {apexpages.addmessages(e);}return null;

     }         
}

The test class is below.
@isTest
public class projectWizardControllerTest {
  private static testmethod void testSubmittedProject() {
 
    projectWizardController controller = new projectWizardController(); 

    //ARRANGE    
    Plan__c plan = new Plan__c();insert plan;
    Project__c project = controller.getProject();
    project.Plan__c = plan.id;
    project.Status__c = 'Submitted';
    insert project;
    
    //ACT
    Test.startTest();
        controller.step1();
        controller.step2();
        controller.step3();                
        controller.submit();           
        PageReference pageRef = Page.manage_project;
        Test.setCurrentPage(pageRef);
        ApexPages.currentPage().getParameters().put('planid',plan.id);
        ApexPages.currentPage().getParameters().put('id',project.id);
        ApexPages.currentPage().setRedirect(true);        
    Test.stopTest();        
    //ASSERT
    System.assertEquals(project.Status__c, 'Submitted');         
}
}
I have the following Apex class that is only getting 57% code coverage.  Test class below as well. I feel like there is something simple that I'm missing. Any help would be appreciated!

public class taskController{

    public Project_Task__c task{get;set;}
    public List<Project_Task_Assignment__c> assignment{get;set;}
    public taskController(){
        task = new Project_Task__c();
        assignment = new List<Project_Task_Assignment__c>();
        task.Project__c = ApexPages.currentPage().getParameters().get('Id');
     
    }
    public void AddRow(){
        assignment.add(new Project_Task_Assignment__c());
    
    }
    public PageReference save(){

     try{
            insert task;
            List<Project_Task_Assignment__c> taskAssignment = new List<Project_Task_Assignment__c>();
            for(Project_Task_Assignment__c c : assignment){
                c.Project_Task__c = task.id;
                taskAssignment.add(c);
    
            }

            if(assignment != null){
                insert taskAssignment;
           }
           
            PageReference taskPage = new PageReference('/apex/manage_task?id=' + task.id);
        taskPage.setRedirect(true);
        return taskPage;
      } 
      
     catch (Exception e) {apexpages.addmessages(e);}return null;        
      
  }  
    
}

*****Test Class*****
@isTest
    public class taskControllerTest{
         private static testMethod void saveTask() {
        
         Account acc = new Account(Name = 'Sample Account'); insert acc;
         Contact con = new Contact(LastName = 'Smith', AccountId = acc.id); insert con;    
         Plan__c plan = new Plan__c(Name = 'Test'); insert plan;
         Project__c project = new Project__c(Name = 'Test', Plan__c = plan.id); insert project;
         
    
            
    
         Test.startTest();
         
         PageReference pageRef = Page.AccountContact;
         
         Project_Task__c task = new Project_Task__c(Project__c = project.id, Name = 'Test Task'); 
         insert task;
         Project_Task_Assignment__c assignment = new Project_Task_Assignment__c(Project_Task__c = task.id, Contact__c = con.id);
         insert assignment;
         Test.setCurrentPage(pageRef);
         taskController controller = new taskController();
         controller.addRow();       

         controller.save();
         pageRef.getParameters().put('id',task.id);   

         Test.stopTest();        
         
         System.assertNotEquals(task.Name, null);
         System.assertNotEquals(assignment, null);         
    
   } 
             
}
I have the following code.

 webService static List<Attachment> getSearchedFiles(String query) {
       String[] searchKeys = query.split(' ');

    for (Integer i = 0; i < searchKeys.size(); i++) {
        searchKeys[i] = '%' + searchKeys[i] + '%';
    }
      system.debug(searchKeys);    
       List<Document_Folder__c> files = [
           select 
            id, 
            (
               select id, Name, Description, BodyLength, CreatedDate, CreatedBy.Name, LastModifiedDate, LastModifiedBy.Name, ParentId,         Parent.Name 
               from attachments 
               where Name LIKE :searchKeys order by Name
            ), 
           from Document_Folder__c
       ];

The debug log shows the correct value that I want.
11:51:47.0 (31583876)|USER_DEBUG|[40]|DEBUG|(%chat%, %talk%)

But no query results are returned. Any thoughts? 

Thanks!
 
Hi, 
I'm trying to deploy and am getting an error with a test class that works fine in sandbox - please help!  Here is the test class:

public class BTProbityCheckTest {

    static testMethod void myBTSendProbityCheckTest(){
    
    Contact newCandy = new Contact (FirstName='Fred', LastName='Flintstone', email='test@testing.com');
    insert newCandy;
   
    BT_Probity_Check__c newBTPC = new BT_Probity_Check__c(Candidate__c= newCandy.id);
    insert newBTPC; 

    PageReference pageRef = Page.BTSendProbityCheck;
    pageRef.getParameters().put('id', newBTPC.id);
    
    Test.setCurrentPageReference(pageRef);
     
    ApexPages.StandardController sc = new ApexPages.standardController(newBTPC);
    BTSendProbityCheckExtension e = new BTSendProbityCheckExtension(sc); 
    
    System.assertEquals(newBTPC.id, e.btpc.id );
    System.assertEquals('test@testing.com', e.btpcEmail);
    System.assertEquals('Fred Flintstone',e.btpc.Full_Name__c); 
    System.assertEquals(String.valueOf(newCandy.Id), e.btpcCandy);
    e.Cancel();
    
    e.SendEmail();
   
    }


The error I get when trying to deploy is:

System.AssertException: Assertion Failed: Expected: Fred Flintstone, Actual: null
Stack Trace: Class.BTProbityCheckTest.myBTSendProbityCheckTest: line 24, column 1

The line is 
System.assertEquals('test@testing.com', e.btpcEmail);

Thanks in advance. 
I have a visualforce component on our Home Page Layout with links, we only want the component to be visible i you have the permission set assign to your profile. How can this be done or can it be done?
Hello! I'm trying to send an email through Apex. Can anyone help me understand why the following code results in this error?
SendEmail failed. First exception on row 0; first error: INVALID_EMAIL_ADDRESS, Email address is invalid: : [toAddresses, ]

Code is below
            Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();                           
            
            String sendEmailsTo = qcRequest.To_Emails__c;        
            String[] toAddresses = sendEmailsTo.split(';');
            System.debug('Emails: ' + toAddresses);
            
            mail.setToAddresses(toAddresses);
            
Thanks for any help you can provide!