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
George Laird 12George Laird 12 

Please help with a quick and dirty test class!

Hello.  I'm very new to apex and programming in general.  I have to deploy this class tonight or tomorrow.  My apex works perfectly but I'm stuck and can't get code coverage for some reason.  Here are the facts:

1. I am using a visualforce page called from a button on the Account page.  

2. In my class I"m getting the Id of the Account from the VF page that the button was pressed from. 

3. Code works great however, when I call the method callCarriers() from the test class, it doesn't have the ID from the button pressed on the Account page of course.  That's the problem.  I tried all sorts of pageref stuff to try and pass the Account ID of the newly created account in the test class but it wont' work. 

4.  I'm BRAND new to coding so my code is very sloppy.  Also I have a lot of things in there that probably don't need to be there, but I'm just trying everything.   Please someone help!


VISUALFORCE PAGE

<apex:page standardController="Account" extensions="CallCarriersForAddyChange"> <apex:form > <apex:commandButton value="Warning: You are about to send an email to carriers! Click here if you are totally sure you want to do this." onclick="javascript&colon;window.alert('Do you want to proceed?');" action="{!callCarriers}"/> <br/> <apex:commandButton value="Ooops, get me out of here!" action="{!forceClose}"/> <apex:inputHidden value="{!Account.OwnerId}"/> </apex:form> </apex:page>



APEX CLASS:

public class CallCarriersForAddyChange {
    //Apex properties or variables

    public Id Id { get; set; }
    public Account act { get; set; }

    //constructor to get the Account record
    public CallCarriersForAddyChange(ApexPages.StandardController controller) {
    act =  (Account) controller.getRecord();
    Id = act.Id;
    System.debug('The Account record: ' + act);
    
    }

    //Method that can is called from the Visual Force page action attribute

    public PageReference callCarriers() {
        
        System.debug('Account Id: ' + Id);
        //build your code logic here
        
        string email;
        List<VRNA__Policy__c> carriers = [SELECT         VRNA__Issuing_Carrier__r.VRNA__Email__c, 
                                          VRNA__First_Named_Insured__c,
                                          VRNA__Policy_Number__c,
                                          VRNA__Issuing_Carrier__r.Name, 
                                          VRNA__Account__r.BillingStreet,
                                          VRNA__Account__r.BillingCity,
                                          VRNA__Account__r.BillingState,
                                          VRNA__Account__r.BillingPostalCode
                                          FROM VRNA__Policy__c 
                                          WHERE VRNA__Account__c =: Id AND RecordTypeID = '012f4000000giyZ'];
     
  List<string> emails = new List<string>();
        system.debug('Carriers: '+carriers);
        
            for(VRNA__Policy__c a : carriers){
            email = a.VRNA__Issuing_Carrier__r.VRNA__Email__c;
               emails.add(email);  
            system.debug('Email List' +emails);
    
        }
        
        for(VRNA__Policy__c p : carriers){
           
          @TestVisible Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
            // Strings to hold the email addresses to which you are sending the email.
            String[] toAddresses = new String[] {p.VRNA__Issuing_Carrier__r.VRNA__Email__c};
            // Assign the addresses for the To and CC lists to the mail object.
            mail.setToAddresses(toAddresses);    
            // Specify the address used when the recipients reply to the email.
            mail.setReplyTo('service@amventure.com');
            // Specify the name used as the display name.
            mail.setSenderDisplayName('Amventure Customer Service');
            // Specify the subject line for your email address.
            mail.setSubject('Policy Mailing Address Change');
            // Set the object Id for merging fields into the template
            //mail.setTargetObjectId(p.Id);
            // The email template ID used for the email
            //mail.setTemplateId('00XM0000000N7NU');
            // Specify the text content of the email.
            mail.setHtmlBody('To Whom It May Concern:<p>' + 'A change to a policy mailing address been requested effective today.<p>' + 'Name Insured: '+p.VRNA__First_Named_Insured__c + '<br/>Policy Number: '+p.VRNA__Policy_Number__c + '<br/>Carrier Name: '+p.VRNA__Issuing_Carrier__r.Name + '<p><b>New Address</b>' +'<br/>Street: '+p.VRNA__Account__r.BillingStreet +'<br/>City: '+p.VRNA__Account__r.BillingCity +'<br/>State: '+p.VRNA__Account__r.BillingState + '<br/>Zip: '+p.VRNA__Account__r.BillingPostalCode);
            // Send the email you have created.
            Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
          
        }

        PageReference pageRef = new PageReference('/'+Id);
        pageRef.setRedirect(true);
        return pageRef; //Returns to the case page
    }
    
     public PageReference forceClose(){
     PageReference page  = page.ForceClose; 
     return page;
     }

TEST CLASS:

@istest(SeeAllData=true)

public class CallCarriersForAddyChangeTest {

    public static testmethod void CallCarriersForAddyChangeTest(){
        
        //create an account
        Account a = new Account(
        Name = 'Test Account',
        BillingStreet='123 main',
        BillingState='Ohio',
        BillingPostalCode='12345',
        RecordTypeId = '012f4000000giww',    
        VRNA__Issuing_Carrier__c = true,
        VRNA__Billing_Company__c = true);
        insert a;
        system.debug('Test Account Id: '+a.Id);
        
        VRNA__Policy__c p = new VRNA__Policy__c(
        Completed_Post_Sale_Checklist__c = 'true',
        VRNA__First_Named_Insured__c = 'tom tomerson',    
        VRNA__Policy_Type__c = 'Crime',
        VRNA__Status__c = 'Written (Sold)',
        VRNA__Account__c = a.Id,
        VRNA__Policy_Number__c = '111111',
        VRNA__Effective_Date__c = Date.today(),
        VRNA__Agency__c = 'AmVenture Insurance Agency, Inc',
        VRNA__Branch__c = 'AmVenture Insurance Agency, Inc',
        VRNA__Department__c = 'Commercial',
        VRNA__Issuing_Carrier__c = a.Id,
        VRNA__Billing_Company__c = a.Id,
        VRNA__Date_First_Written__c = Date.today(),
        VRNA__Policy_Issuing_State_picklist__c = 'OH',
        VRNA__Package_Type__c = 'Monoline',
        VRNA__Primary_Producer__c = '005f4000000yGSY',   
        RecordTypeId = '012f4000000giyZ');
        insert p;
        
        test.startTest(); 
        
        ApexPages.StandardController sc = new ApexPages.StandardController(a);
        CallCarriersForAddyChange c = new CallCarriersForAddyChange(new ApexPages.StandardController (new Account()));
        PageReference pageRef = Page.ExecuteCallCarriersForAddyChange;
        Test.setCurrentPage(pageRef);
        ApexPages.currentPage().getParameters().put('Idx', a.Id);
        c.callCarriers();
        c.forceClose();
        test.stopTest(); 

    }
}

 
Best Answer chosen by George Laird 12
Maharajan CMaharajan C
HI Georege :

Please change the below 5 lines with below updated code:

        ApexPages.StandardController sc = new ApexPages.StandardController(a);
        CallCarriersForAddyChange c = new CallCarriersForAddyChange(new ApexPages.StandardController (new Account()));
        PageReference pageRef = Page.ExecuteCallCarriersForAddyChange;
        Test.setCurrentPage(pageRef);
        ApexPages.currentPage().getParameters().put('Idx', a.Id);


        Update Lines for above lines:

        ApexPages.StandardController sc = new ApexPages.StandardController(a);
        CallCarriersForAddyChange  c = new CallCarriersForAddyChange (sc);
        
        PageReference pageRef = Page.ExecuteCallCarriersForAddyChange;
        pageRef.getParameters().put('id', String.valueOf(a.Id));
        Test.setCurrentPage(pageRef);



1. System.debug won't work in the test class. Use the System.assert methods to check your values.
2, Don't use the hard coded record types use the below methoda to get the record type id with the help of record type developer name . you can use the same method in the test class to get the record type id:

Id RecordTypeIdContact = Schema.SObjectType.Contact.getRecordTypeInfosByName().get('DeveloperNameOfRecordType').getRecordTypeId();


    Can you please Let me know if it helps or not!!!

    If it helps don't forget to mark this as a best answer!!!

    
Thanks,
    Maharajan.C

All Answers

Maharajan CMaharajan C
HI Georege :

Please change the below 5 lines with below updated code:

        ApexPages.StandardController sc = new ApexPages.StandardController(a);
        CallCarriersForAddyChange c = new CallCarriersForAddyChange(new ApexPages.StandardController (new Account()));
        PageReference pageRef = Page.ExecuteCallCarriersForAddyChange;
        Test.setCurrentPage(pageRef);
        ApexPages.currentPage().getParameters().put('Idx', a.Id);


        Update Lines for above lines:

        ApexPages.StandardController sc = new ApexPages.StandardController(a);
        CallCarriersForAddyChange  c = new CallCarriersForAddyChange (sc);
        
        PageReference pageRef = Page.ExecuteCallCarriersForAddyChange;
        pageRef.getParameters().put('id', String.valueOf(a.Id));
        Test.setCurrentPage(pageRef);



1. System.debug won't work in the test class. Use the System.assert methods to check your values.
2, Don't use the hard coded record types use the below methoda to get the record type id with the help of record type developer name . you can use the same method in the test class to get the record type id:

Id RecordTypeIdContact = Schema.SObjectType.Contact.getRecordTypeInfosByName().get('DeveloperNameOfRecordType').getRecordTypeId();


    Can you please Let me know if it helps or not!!!

    If it helps don't forget to mark this as a best answer!!!

    
Thanks,
    Maharajan.C
This was selected as the best answer
George Laird 12George Laird 12
@Maharajan C 

Thank you so much!  But it's still not working.  I thought maybe adding another account may help.  The ID doesn't look like it's passing over to my method in the other class.  I'm still at the same code coverage.  Here is my updated APEX class.  I'm also including a screen shot of the code coverage so you can see what's going wrong. 



APEX:

public class CallCarriersForAddyChange {
    //Apex properties or variables

     
    public Id Id { get; set; }
    public Account act { get; set; }

    //constructor to get the Account record
    public CallCarriersForAddyChange(ApexPages.StandardController controller) {
    act =  (Account) controller.getRecord();
    Id = act.Id;
    System.debug('The Account record: ' + act);
    
    }

    //Method that can is called from the Visual Force page action attribute
    public PageReference callCarriers() {
        

        System.debug('Account Id: ' + Id);
        //build your code logic here
        
        string email;
        List<VRNA__Policy__c> carriers = [SELECT VRNA__Issuing_Carrier__r.VRNA__Email__c, 
                                          VRNA__First_Named_Insured__c,
                                          VRNA__Policy_Number__c,
                                          VRNA__Issuing_Carrier__r.Name, 
                                          VRNA__Account__r.BillingStreet,
                                          VRNA__Account__r.BillingCity,
                                          VRNA__Account__r.BillingState,
                                          VRNA__Account__r.BillingPostalCode
                                          FROM VRNA__Policy__c 
                                          WHERE VRNA__Account__c =: Id AND RecordTypeID = '012f4000000giyZ'];
        List<string> emails = new List<string>();
        system.debug('Carriers: '+carriers);
        
            for(VRNA__Policy__c a : carriers){
            email = a.VRNA__Issuing_Carrier__r.VRNA__Email__c;
               emails.add(email);  
            system.debug('Email List' +emails);
    
        }
        
        for(VRNA__Policy__c p : carriers){
           
          @TestVisible Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
            // Strings to hold the email addresses to which you are sending the email.
            String[] toAddresses = new String[] {p.VRNA__Issuing_Carrier__r.VRNA__Email__c};
            // Assign the addresses for the To and CC lists to the mail object.
            mail.setToAddresses(toAddresses);    
            // Specify the address used when the recipients reply to the email.
            mail.setReplyTo('service@amventure.com');
            // Specify the name used as the display name.
            mail.setSenderDisplayName('Amventure Customer Service');
            // Specify the subject line for your email address.
            mail.setSubject('Policy Mailing Address Change');
            // Set the object Id for merging fields into the template
            //mail.setTargetObjectId(p.Id);
            // The email template ID used for the email
            //mail.setTemplateId('00XM0000000N7NU');
            // Specify the text content of the email.
            mail.setHtmlBody('To Whom It May Concern:<p>' + 'A change to a policy mailing address been requested effective today.<p>' + 'Name Insured: '+p.VRNA__First_Named_Insured__c + '<br/>Policy Number: '+p.VRNA__Policy_Number__c + '<br/>Carrier Name: '+p.VRNA__Issuing_Carrier__r.Name + '<p><b>New Address</b>' +'<br/>Street: '+p.VRNA__Account__r.BillingStreet +'<br/>City: '+p.VRNA__Account__r.BillingCity +'<br/>State: '+p.VRNA__Account__r.BillingState + '<br/>Zip: '+p.VRNA__Account__r.BillingPostalCode);
            // Send the email you have created.
            Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
          
        }

        PageReference pageRef = new PageReference('/'+Id);
        pageRef.setRedirect(true);
        return pageRef; //Returns to the case page
    }
    
     public PageReference forceClose(){
     PageReference page  = page.ForceClose; 
     return page;
     }
    
}


NEW TEST CLASS:

@istest(SeeAllData=true)

public class CallCarriersForAddyChangeTest {

    public static testmethod void CallCarriersForAddyChangeTest(){
        
        //create an account
        Account a = new Account(
        Name = 'Test Account',
        VRNA__Email__c = 'george@amventure.com',    
        BillingStreet='123 main',
        BillingState='Ohio',
        BillingPostalCode='12345',
        RecordTypeId = '012f4000000giww',    
        VRNA__Issuing_Carrier__c = true,
        VRNA__Billing_Company__c = true);
        insert a;
        system.debug('Test Account Id: '+a.Id);
        
        Account a2 = new Account(
        Name = 'Test Account2',
        VRNA__Email__c = 'george@amventure.com',    
        BillingStreet='123 main',
        BillingState='Ohio',
        BillingPostalCode='12345');   
        insert a2;
        system.debug('Test Account2 Id: '+a2.Id);
        
        VRNA__Policy__c p = new VRNA__Policy__c(
        Completed_Post_Sale_Checklist__c = 'true',
        VRNA__First_Named_Insured__c = 'tom tomerson',    
        VRNA__Policy_Type__c = 'Crime',
        VRNA__Status__c = 'Written (Sold)',
        VRNA__Account__c = a2.Id,
        VRNA__Policy_Number__c = '111111',
        VRNA__Effective_Date__c = Date.today(),
        VRNA__Agency__c = 'AmVenture Insurance Agency, Inc',
        VRNA__Branch__c = 'AmVenture Insurance Agency, Inc',
        VRNA__Department__c = 'Commercial',
        VRNA__Issuing_Carrier__c = a.Id,
        VRNA__Billing_Company__c = a.Id,
        VRNA__Date_First_Written__c = Date.today(),
        VRNA__Policy_Issuing_State_picklist__c = 'OH',
        VRNA__Package_Type__c = 'Monoline',
        VRNA__Primary_Producer__c = '005f4000000yGSY',   
        RecordTypeId = '012f4000000giyZ');
        insert p;
        
        test.startTest(); 
        
        ApexPages.StandardController sc = new ApexPages.StandardController(a);
        CallCarriersForAddyChange  c = new CallCarriersForAddyChange (sc);
        PageReference pageRef = Page.ExecuteCallCarriersForAddyChange;
        pageRef.getParameters().put('id', String.valueOf(a2.Id));
        Test.setCurrentPage(pageRef);
        c.callCarriers();
        c.forceClose();
        test.stopTest(); 
        
    }
}


COVERAGE:


User-added image

User-added image
 
George Laird 12George Laird 12
@Maharajan C

Actually, the ID may be passing over now, but i'm still not getting anymore code coverage.  Why are most of the lines in the query not getting covered?
 
Maharajan CMaharajan C
Looks Like your VRNA__Policy__c  record is not created.

So check all your mandatory fields are inserted in VRNA__Policy__c record in test class .

In the UI what all things your are giving to store the VRNA__Policy__c record those all data should be iin the test class and check any validation rule or triggers are block your test class.

To Easily get your test class issue run your test class by below way :

Setup --> Develop --> Apex Test Execution --> Select Test --> Choose the class --> Run.

don't use the developer console am always using the above ways.