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
Alex SkemprisAlex Skempris 

User choose record to delete on Visualforce - Controller deletes - Test Class

Hello 

I've built a VF page along with a controller extension where the user is able to delete a record via an action button. I've set the chosen record id to go to my controller and from there the controller deletes the the record via a DML Statement. What I'm struggling with is writing the test code for it as every delete resource I've found has failed. Or I've written it incorrectly.

I would be grateful for some assistance on that last bit of my test class. Here's my code below:

*****VG PAGE*****
<apex:page standardController="Opportunity" extensions="ClaimAndExtensionsROR" title="SIPP Claim Internal Questionnaire - Previous Claim Details " sidebar="false" showHeader="false">
<br>
<div style="text-align:center;font-size: 30px;">
<apex:outputlabel value="SIPP Claim Internal Questionnaire - Previous Claim Details"/>
</div>
</br>
<apex:pageMessages />
<apex:form >
<script type="text/javascript">
function CloseWindow()
{
window.top.close();
UpdateOpener();
}
</script>

<apex:pageBlock mode="mainDetail">
<apex:pageBlockButtons location="Bottom" >
<apex:commandButton action="{!save}" value="Save Changes" />
<apex:commandButton action="{!save}" value="Save and Close" status="closer" oncomplete="CloseWindow();" />
<apex:actionStatus startText="(Saving... Window will close shortly)" stopText="" id="closer"/>
</apex:pageBlockButtons>
</apex:pageBlock>

<apex:pageBlock title="Pensions" tabstyle="SIPP_Operator__c">
<apex:outputPanel id="PensionMessage">
<apex:pageMessage summary="{!primarymsg}" severity="error" strength="3" rendered="{!primarymsgck}" />
</apex:outputPanel> <div align="center" draggable="false" >
<apex:commandButton action="{!newPensions}" value="New Pension" rendered="{!ISNULL(Opportunity.SIPP__c)}" rerender="PensionsList"/> </div>
<apex:outputPanel id="PensionsList">
<apex:repeat value="{!Pensions}" var="pen" >
<apex:pageBlockSection columns="1" title="Pension {!pen.Name}" collapsible="true">
<apex:pageBlockSectionItem >
<apex:pageBlockSection columns="2">
<apex:pageBlockSection columns="1">
<apex:outputField value="{!pen.Person_Account__c}"/>
<apex:inputField value="{!pen.SIPP_Provider__c}"/>
<apex:inputField value="{!pen.Date_SIPP_opened__c}" />
<apex:inputField value="{!pen.Pension_Category__c}"/>
<apex:inputField value="{!pen.Pension_Type__c}" />
</apex:pageblockSectionItem>
<apex:commandButton value="Delete Pension" action="{!deletePensions}" rendered="{!ISNULL(Opportunity.SIPP__c)}" rerender="PensionsList, PensionMessage">
<apex:param name="PensionsIdent" value="{!pen.id}" assignTo="{!chosenPensionsId}"/> <!-- id goes to the controller --->
</apex:commandButton>
</apex:pageBlocksection>
</apex:repeat>
</apex:outputPanel>
</apex:pageBlock>


****THE CONTROLLER****

public class CtrlExtension {
   public ApexPages.StandardController std;

   public Id chosenPensionsId {get; set;}
   public List<SIPP_Operator__c> Pensions;

public ClaimAndExtensionsROR(ApexPages.StandardController stdCtrl){
        std = stdCtrl;
        List<string> fields = new list<string>{'AccountId', 'Previous_Relevant_Claim__c', 'StageName', 'Opportunity_Sub_Stage__c', 'SIPP__c', 'Previous_Relevant_Claim__r.SIPP__c', 'Previous_Relevant_Claim__r.Financial_Advice__c', 'Total_Compensation_Payable__c', 'Previous_Relevant_Claim__r.Introducer_Agent__c', 'Introducer_Agent__c'};

        if(!Test.isRunningTest())    
           {
        stdCtrl.addFields(fields);    
         }
    }

    public Opportunity getOpportunity()
    {
     return (Opportunity) std.getRecord();
    }

public void newPensions()
    {
      if (updatePensions())
       {
           SIPP_Operator__c pen=new SIPP_Operator__c(Person_Account__c = getOpportunity().Accountid);   
           insert pen;      
            
           Pensiontoinsert = pen.id;
           
          Pensions=null;

       }
    }

public void deletePensions()
    
    {
       if (updatePensions())
       {
          if (null!=chosenPensionsId)
          {
             SIPP_Operator__c pen = new SIPP_Operator__c(Id=chosenPensionsId);
              try{
              delete pen;
              }
              catch (System.DMLException e)
              {  
               primarymsgck = true;
               primarymsg = 'Error - You cannot delete a Pension that is already associated with a claim. Please inform your Salesforce Administrator.';
              }
        
           // null the contacts list so that it is rebuilt
              Pensions=null;
              chosenPensionsId=null;
          }
       }
    }

****TEST CLASS****

@isTest
public class ClaimAndExtensionsRORTestClass {

    Static ClaimAndExtensionsROR clext;


Account testacc = new Account();
        testAcc.LastName = 'test';
        testacc.Email_Address__c = 'alex@brangaene.com';
        testacc.PersonEmail = 'alex@brangaene.com';
        testacc.RecordTypeId = '01258000000VBdv';
        insert testacc;
        
        SIPP_Operator__c pen = new SIPP_Operator__c();
        pen.Person_Account__c = testacc.Id;
        insert pen;
        clext.newPensions();

        PageReference pref = Page.SIPP_Claim_Internal_Questionnaire_PRC;
        pref.getParameters().put('id', opp.id);
        test.setCurrentPage(pref);
        ApexPages.StandardController con = new ApexPages.StandardController(opp);
        clext = new ClaimAndExtensionsROR(con);

//Testing deletion
pen.id = clext.chosenpensionsId;
​delete pen

Clext.deletePensions();
}


Many thanks
Alex

 
Gaurish Gopal GoelGaurish Gopal Goel
Hi Alex,

Please try this code and read about best practices to write Test Apex. You are not supposed to hardcode any record ID anywhere. Please do not forget to mark this thread as SOLVED and answer as the BEST ANSWER if it helps address your issue.​
@isTest
public class ClaimAndExtensionsRORTestClass 
{
	static testMethod void Test1()
	{
		Account testacc = new Account();
        testAcc.LastName = 'test';
        testacc.Email_Address__c = 'alex@brangaene.com';
        testacc.PersonEmail = 'alex@brangaene.com';
        testacc.RecordTypeId = '01258000000VBdv';
        insert testacc;
        Opportunity opp = new Opportunity(AccountId=testacc.Id,Name='test',closeDate=Date.today(),stageName='Open');
		insert opp;
        SIPP_Operator__c pen = new SIPP_Operator__c();
        pen.Person_Account__c = testacc.Id;
        insert pen;
		
		ApexPages.StandardController stdCtrl = new ApexPages.StandardController(opp);
		ClaimAndExtensionsROR clext = new ClaimAndExtensionsROR(stdCtrl);
		Test.startTest();
			clext.newPensions();
			Clext.deletePensions();
		Test.stopTest();
	}
}

Regards,
Gaurish
Alex SkemprisAlex Skempris
Hi Gaurish,

Thank you for your reply but unfortunately the solution doesn't work. It seems to be covering the line where the method is (public void deletePensions()) but not the rest of it. Not the delete neither the try/catch block. 

I have also updated the code as per your suggestion and used more test data and removed the Id for the account.

Thanks
Alex

 
Gaurish Gopal GoelGaurish Gopal Goel
Hi Alex, I have shown you the way to write a test class. Now you will have to try yourself to increase the code coverage. If you stuck somewhere then you can post your code and I will tell where the problem is. Thanks.