0
  public PageReference createAccountContact(){
        newAccount = false;
        PageReference pr = new PageReference('/apex/NewAccountContact'); 
        pr.setRedirect(false);
        return pr; 
    }

This is simply called from a button on a VF page, which uses the account standard controller and an extension (which this pageReference is on). A user can click this button without having selected any data. The parent VF page itself is ran from it's own tab so it doesn't pass data until other classes are called, this buttons opens a different VF page.

I've tried

 TestDataUtility_Acct tdAz = new TestDataUtility_Acct();
            Account objaccount = tdAz.crtAccount();
            insert(objaccount);
        pageReference pref = page.TradeShow;
           Test.setCurrentPage(pref);
           test.startTest();

            ApexPages.StandardController con = new ApexPages.StandardController(objaccount);
     TradeShow_Ctl reDir = new TradeShow_Ctl(con);
        reDir.createAccountContact();

           test.stopTest();

Now i wouldn't use the testdatautility to create an account...because i shouldn't need since the VF page in it's default state does not access any account data until you click a separate button. But i can't call on the createAccountContact method without defining a standard controller. All i want is code coverage i don't care how it happens, because i know this works.

Here's the only portion of the system that interacts with this method piece of code

<div>
                    <apex:commandLink action="{!createAccountContact}" value="Add New Account / Contact" id="theCommandLink" style="float:right;padding-right: 2%;"/>
                </div>

Someone asked if my controller had a try catch: here it is, but it's unrelated to the problem method.

   public pageReference saveAccountContact(){
        List<Contact> contactList = new List<Contact>();
        List<Contact> insertcontactList = new List<Contact>();

        objOpportunity.AccountId=objTSContact.AccountId;

        RecordType objRT = new RecordType();
        objRT = [SELECT id, name from RecordType where sObjectType = 'Contact' AND DeveloperName='Sales'];
        Savepoint s = Database.setSavepoint();
        if(objOpportunity.AccountID != null){
           // contactList = [SELECT Id,Name,Email,Phone FROM Contact WHERE AccountID=:objOpportunity.AccountID AND  Email=:objContact.Email AND Email!=''];

            try{
                objContact.AccountId = objOpportunity.AccountID;
                objContact.RecordTypeID = objRT.id;   
                insert objContact;
                ApexPages.addmessage(new ApexPages.message(ApexPages.severity.CONFIRM,' Contact added successfully!'));       

              //omitted as duplicate checker is enabled     
              //code for validation of duplicate contacts    
              /*  if(contactList.size()>0){
                    ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error,' Contact  Already Exists'));
                    return null;
                }
                else{
                    insert objContact;
                    ApexPages.addmessage(new ApexPages.message(ApexPages.severity.CONFIRM,' Contact added successfully!')); 
                }*/


            }catch(Exception e){
                Database.rollBack(s);
                ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error,e.getMessage()));//' Record Not Saved!'));
                return null;    
            }
        }else{
            try{
                insert ObjAccount;
                objOpportunity.AccountID = ObjAccount.Id;
                objTSContact.AccountId =ObjAccount.Id;

                objContact.AccountId = ObjAccount.id;
                objContact.RecordTypeID = objRT.id;
                insert objContact;
                ApexPages.addmessage(new ApexPages.message(ApexPages.severity.CONFIRM,'Account and Contact added successfully!'));

            }catch(Exception e){
                objContact.id = null;
                ObjAccount.Id = null;
                if(ObjAccount.Name!=null && ObjAccount.Name !='') objTSContact.AccountId =null;
                Database.rollBack(s);
                ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error,e.getMessage()));//' Record Not Saved!'));
                return null;
            }
        }

below is the constructor for the extension

 public TradeShow_Ctl(ApexPages.StandardController controller) {
        newAccount = false;
        objAccount = new Account();
        objContact = new Contact();
        selectContactId =null;
        listSelectedContactId = new List<String>();
        objOpportunity = new Opportunity();
        objTSContact = new Contact();
        campaignList = new List<Campaign>();

        //SOQL for campaign
        campaignList = [SELECT Id,Name,
                                 (SELECT Id, name from Opportunities 
                                  WHERE RecordType.DeveloperName='Trade_Show_Master') 
                        FROM Campaign 
                        WHERE NumberOfOpportunities > 0 
                        and Active_Trade_Show__c=true order by lastmodifiedDate desc limit 1];

        if(campaignList.size()>0){
            campID = campaignList[0].id;
            campName = campaignList[0].Name;
            //campaignPicklist = false;
        }else if(campaignList.size()==0){
            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.WARNING,' No Trade Show held Today'));
        }
        ContactSelect = new List<SelectOption>();
        optionsRecSale = new List<selectOption>();
        optionsIncRepConv = new List<selectOption>();
        optionsConfidenceLevel = new List<selectOption>();
        optionsRevenueModel = new List<selectOption>();

        //Options for Revenue Model for MJP Products
        optionsRevenueModel.add(new selectOption('MJP WAP','WAP'));
        optionsRevenueModel.add(new selectOption('MJP Flat Fee','FLAT'));
        optionsRevenueModel.add(new selectOption('MJP Participation','PART'));

        //Select Radio for REC/SALE 
        Schema.DescribeFieldResult recSaleResult = OpportunityLineItem.REC_SALE__c.getDescribe();
        List<Schema.PicklistEntry> rec_sale_values = recSaleResult.getPickListValues();
        for (Schema.PicklistEntry a : rec_sale_values) {
            optionsRecSale.add(new selectOption(a.getValue(), a.getLabel()));
        }

        //Select Radio for INC/REP/CONV
        Schema.DescribeFieldResult incRepConvResult = OpportunityLineItem.INC_REP_CONV__c.getDescribe();
        List<Schema.PicklistEntry> inc_rep_conv_values = incRepConvResult.getPickListValues();
        for (Schema.PicklistEntry a : inc_rep_conv_values) {
            optionsIncRepConv.add(new selectOption(a.getValue(),a.getLabel()));
        }

        //Select Radio for CONFIDENCE LEVEL
        Schema.DescribeFieldResult confidenceLevelResult = OpportunityLineItem.CONFIDENCE_LEVEL__c.getDescribe();
        List<Schema.PicklistEntry> confidenceLevelvalues = confidenceLevelResult.getPickListValues();
        for (Schema.PicklistEntry a : confidenceLevelvalues) {
            optionsConfidenceLevel.add(new selectOption(a.getValue(), a.getLabel()));
        }
        List<SelectOption> listRadio =new List<SelectOption>();
        Integer j=0;
        for(Integer i=optionsConfidenceLevel.size()-1;i>=0;i--){
            listRadio.add(optionsConfidenceLevel[i]);
            j++;
        }
        optionsConfidenceLevel = listRadio;

        /*if(campId!=null){
            getProductList();
        }*/

    }
3
  • Do you have any try catch statements in your test methods or in the main class. If yes, then try commenting them out temporarily and run your test class to check if it's causing any exception. Commented Sep 12, 2019 at 16:43
  • I do but it's for a separate unrelated pageReference, i'll updated my main post with it
    – ensir
    Commented Sep 12, 2019 at 16:53
  • Does the unit test pass or fail?
    – David Reed
    Commented Sep 13, 2019 at 2:06

1 Answer 1

1

This unit test should cover the code shown. Because createAccountContact() contains no branching logic, any unit test that

  1. Causes createAccountContact() to be executed.
  2. Does that throw an exception or fail an assertion.

should cover it successfully.

Because you've plainly accomplished (1), it seems the problem is likely (2) - somewhere, potentially in code that you have not shown us, an exception is being thrown, or some assertion fails. Carefully review your logs and your test results to confirm this possibility.

All i want is code coverage i don't care how it happens, because i know this works.

Now these, these are famous last words.

Your unit tests should never* just be code coverage. This is a bad practice. Your unit tests should always make assertions to validate the behavior of your code.

Remember that your code will likely have a lifespan measured in years, and persons other than you will be required to work on it, understand it, and test it. Remember that your code has dependencies it relies upon to behave as you understand it to behave - and your unit tests are your one and only guard to catch regressions caused by changes in those dependencies before they harm your users.

Please review the unit testing resources we collect under the canonical-qa tag for more on writing good unit tests.

* There are a small number of exceptions to this rule, mostly for the handful of corner cases that cannot be tested as such on the Salesforce platform.

2
  • the method is only called on from a commandLink, no values are passed to it, and the code in no way interacts with any other part of the controller. Would it be possible in a test class to call on the commandLink. Say the
    – ensir
    Commented Sep 12, 2019 at 16:11
  • +1 for Now these, these are famous last words.
    – cropredy
    Commented Sep 12, 2019 at 19:31

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .