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
Zoom_VZoom_V 

Help with test code

I am trying to figure out how to write the test code for this VF controller and a Trigger which will work on the same object. I've never written test code before, so I'm quite desperate right now. I'm studying the online help and am not really getting too far. Can anybody help with this ?

This code is creating a junction record between a Regulation__c record and a Vendor_Product__c record. Basically, the class queries each individual selection from a list (selectedvalues). Each selection in the list represents a corresponding Vendor_Product record. The class places them into a multi-valued field (Products_Affected__c) in the Regulations__c object. It queries each value to confirm that it wasn't already added to the field before.

The trigger then takes each value of the Products_Affected__c field, queries it to find the corresponding Vendor_Product__c record, and upserts a new junction record with the Products_Affected_Regulation_Entry__c object.

Here is the Class (VF controller) :
 
public class RegulationsVFControllerEdit {
private final Regulation__c main;
public String rightOptionsHidden { get; set; }
public String leftOptionsHidden { get; set; }
public String selectedMulPickKeyTech{get;set;} 
public string lookupid{get;set;}
public String message { get; set; }
public List<SelectOption> options { get; set; }
public List<SelectOption> selectedSubs2 { get; set; }
public String selectedItems { get; set; }
public String mainid {get;set;}
public String coid {get;set;}    
    public RegulationsVFControllerEdit(apexpages.standardcontroller controller)
        {
        selectedSubs2 = new list<SelectOption>();
        this.main = (Regulation__c) controller.getRecord();
        }

    public pageReference  execute()
        {
        return null;
        }

    public list<selectoption> getitems()
        {
        lookupid=main.Vendor__c;
        mainid=main.id;
        //Set<String> selectedItems = new Set<String>();
        selectedItems=main.Products_Affected__c;
        coid = main.id;
        selectedMulPickKeyTech=main.Products_Affected__c;

        List<selectoption> options= new list<selectoption>();
        if(lookupid != null)
            {
                    if(selectedMulPickKeyTech !=null)
                    {
                    selectedMulPickKeyTech=selectedMulPickKeyTech.replace('[','');                
                    selectedMulPickKeyTech=selectedMulPickKeyTech.replace(']','');

                    String[] selectedvalues = selectedMulPickKeyTech.split(',');
                    System.debug('selectedMulPickKeyTechLine43 ########'+selectedMulPickKeyTech); 
                    System.debug('selectedvaluesLine44 ########'+selectedvalues);         
                    selectedSubs2 = new list<SelectOption>();
                    for (String selectedvalue: selectedvalues) 
                        {
                        selectedSubs2.add(new SelectOption(selectedvalue,selectedvalue));
                        }

                     }   
             System.debug('lookupid ########'+lookupid); 
             System.debug('selectedSubs2Line52 ########'+selectedSubs2);  
             System.debug('selectedMulPickKeyTechLine54 ########'+selectedMulPickKeyTech); 
           Vendor_Profile__c a =[select name , (select name from Vendor_Products__r) from Vendor_Profile__c where id =:lookupid];
                for(Vendor_Product__c s : a.Vendor_Products__r)
                    {
                        //check that selected items dont already contain the keys
                        //if(!selectedItems.contains(s.name))
                    options.add(new SelectOption(s.name,s.name));
                    }
            }

            else
            options.add(new SelectOption('None','None'));
            return options;

        }

    public PageReference save()
        {
        message = null ;       
        Boolean first = true;
        if (selectedSubs2.size() > 0)
            {
           for ( SelectOption so : selectedSubs2 ) 
            {
                if (first) 
                    {
                    message = message ;
                    }
                    message = message + ', ' + so.getValue() ;
                    first = false;
            }   

                message = message.removeStart('null, ');
                message = message.normalizeSpace();
                message = '['+message+']';
                main.Products_Affected__c=message;
                }
        update main;

      System.debug('coid ########'+coid);

      //PageReference pr = new PageReference('/a7w/o');
      PageReference pr = new PageReference('/'+ mainid);

          pr.setRedirect(true);
          return pr;

        }
}

This is the trigger which runs after the record is saved :
 
trigger AutoCreateSubOnRegulation on Regulation__c(after insert,after update)
{
    //Since, we need two values from Regulation__c to be populated on the new Products_Affected_Regulation_Entry__c record.
    //So, taking a Map instead of list. Earlier, List<String> subAccNames=new List<String>();
    //Map of subAccountNames and Regulation__c Record.</b>
    Map<String, Regulation__c> subAccNames=new Map<String, Regulation__c>();

    for(Regulation__c newCont: Trigger.New) 
    {
        //Checking of the field is empty or not.</b>
        if(newCont.Products_Affected__c!=Null && newCont.Products_Affected__c!='') 
        {
            system.debug('newCont.Products_Affected__c---->'+newCont.Products_Affected__c);
            String temp=newCont.Products_Affected__c.normalizeSpace();
            temp=temp.replace(']',''); //No need for this if comma seperated values as I have taken.
            temp=temp.replace('[',''); //No need for this if comma seperated values as I have taken.</b>

            //Iterate the number of values in the temp variable by slitting them by comma
            //add put them in subAccNames</b>
            for(String acctName: temp.split(','))
            {
                subAccNames.put(acctName.normalizeSpace(), newCont);
                system.debug('subAccNames !!! '+subAccNames); 
            }
        }
    }

    //Take a Map of Name and Record for holding Vendor_Product__c Name and Vendor_Product__c Record.</b>
    Map<String, Vendor_Product__c> subAccIdsByName=new Map<String, Vendor_Product__c>();

    //Iterate over the Vendor Product records and create a Map with Venfor Product Id as Key and Vendor Product Record as Value.</b>
    for(Vendor_Product__c subacc: [SELECT Id, Vendor__c, Name FROM Vendor_Product__c WHERE Name IN :subAccNames.keySet()]) 
    {
        //Putting record in place of Id, as value in the map.</b>
        subAccIdsByName.put(subacc.Name, subacc);
        System.debug('subAcc Name and ID='+subacc.Name +'Id='+subacc.id+'Vendor_c='+subacc.Vendor__c);
    }

//&nbsp;   //This will hold the Products_Affected_Regulation_Entry__c records to be upserted.</b>
    List<Products_Affected_Regulation_Entry__c> subs = new List<Products_Affected_Regulation_Entry__c>();

    //Iterating over subAccNames Map.
    //No need to iterate again over Regulation__c records as we have already taken the Regulation__c record in the subAccNames Map.
    //Earlier: for (Regulation__c newContract : Trigger.New)</b>
    for(String ref1: subAccNames.keySet()) 
    {
        //Iterate over the subAccIdsByName Map.</b>
        for(String ref2: subAccIdsByName.keySet())
        {
            //Match if the Name in the subAccNames Map is equal to Name in the subAccIdsByName Map.</b>
            if(ref1==ref2)
            {
                Products_Affected_Regulation_Entry__c ssoc = new Products_Affected_Regulation_Entry__c();
                ssoc.Regulation__c=subAccNames.get(ref1).Id;
                //Access Vendor Product Id from the Map.</b>
                ssoc.Vendor_Product__c=subAccIdsByName.get(ref2).Id;
                //Access Vendor__c from the Map.</b>
                ssoc.Vendor__c=subAccIdsByName.get(ref2).Vendor__c;
                //Access Name from the Map.</b>
                ssoc.Regulation_and_Product__c=subAccNames.get(ref1).Name+'~'+subAccIdsByName.get(ref2).Id;
                //Put the records in the </b>subs </b>list.</b>
                subs.add(ssoc);
            }
        }
    }

    upsert subs Regulation_and_Product__c;
}

Like I said, I'm trying to learn it for myself, but that's going to take some time. I'd appreciate any kind of help I can get. 

Thank you.
Bhaswanthnaga vivek vutukuriBhaswanthnaga vivek vutukuri
Hi, Test class should look some thing like this 
@isTest
private class RegulationsVFControllerEditTest
{
	// Creating test data. Make sure that you have given all required fields and satisfying all the formula and validation rules
	Vendor_Product__c  ven = new Vendor_Product__c ();
	ven.name = 'asfdsa';
	ven.otherrequirefield = 'sadfas';
	insert ven;

	Regulation__c reg= new Regulation__c();
	reg.name = 'sample';
	reg.vendor__c = ven.id;
	reg.Products_Affected__c = 'samplevalue';
	insert reg;

	// Test the code by passing test data
	ApexPages.StandardController sc = new ApexPages.StandardController(reg);
	RegulationsVFControllerEdit regControllerEdit = new RegulationsVFControllerEdit(sc);
	regControllerEdit.execute();
	regControllerEdit.getItems();
	PageReference pr = regControllerEdit.save();

	System.assertEquals(pr,'/'+reg.id);


}
Zoom_VZoom_V
Thank you very much for your input. I've tried this code but keep getting errors. I've altered it a little to try and get it to work properly but still getting other errors : 
 
@isTest
private class RegulationsVFControllerEditTest
{
    // Creating test data. Make sure that you have given all required fields and satisfying all the formula and validation rules
    Vendor_Product__c  ven = new Vendor_Product__c (
    ven.name == 'asfdsa',
    ven.Vendor_Summary__c = 'xxx'),
    insert ven;

    Regulation__c reg= new Regulation__c(
    reg.name = 'sample',
    reg.vendor__c = ven.id,
    reg.Products_Affected__c = 'samplevalue'),
    insert reg;

    // Test the code by passing test data
    ApexPages.StandardController sc = new ApexPages.StandardController(reg);
    RegulationsVFControllerEdit regControllerEdit = new RegulationsVFControllerEdit(sc);
    regControllerEdit.execute();
    regControllerEdit.getItems();
    PageReference pr = regControllerEdit.save();

    System.assertEquals(pr,'/'+reg.id);


}


As it is now, I am getting an "unexpected toekn 'insert' at line 8 column 4" error. 

If I comment out the insert commands to try and see if I can get it to just save properly, I then get an error : "unexpected token: ',' at line 23 column 26" - which is referring to the PageReference line. 

Any ideas on this ? 

Thank you so much for your help.

Bhaswanthnaga vivek vutukuriBhaswanthnaga vivek vutukuri

Hey you have gone with many syntax errors 

Try this 

@isTest
private class RegulationsVFControllerEditTest
{
    // Creating test data. Make sure that you have given all required fields and satisfying all the formula and validation rules
    Vendor_Product__c  ven = new Vendor_Product__c (
    ven.name == 'asfdsa',
    ven.Vendor_Summary__c = 'xxx');
    insert ven;

    Regulation__c reg= new Regulation__c(
    reg.name = 'sample',
    reg.vendor__c = ven.id,
    reg.Products_Affected__c = 'samplevalue');
    insert reg;

    // Test the code by passing test data
    ApexPages.StandardController sc = new ApexPages.StandardController(reg);
    RegulationsVFControllerEdit regControllerEdit = new RegulationsVFControllerEdit(sc);
    regControllerEdit.execute();
    regControllerEdit.getItems();
    PageReference pr = regControllerEdit.save();

    System.assertEquals(pr,'/'+reg.id);


}