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
LavanyaLavanya 

Help me on writing a test class for my apex code

Hi All,I have created a Apex code for my custom object button which will create a 10 opportunity. Now i need to move this to production. I didn't have any idea about writting test class, Can anyone help me how to write test class for this,also tell me any link about class. I am new to salesforce this is the first time I am going to write test class.Thanks in advance,waiting for your reply.

 

Apex Code:

 

public class Conversion_site
{
    private Site__c siteObj;
    public String Sales_pop {get; set;}
    private List<Opportunity> lstOpp = new List<Opportunity>();
    public List<opportunityRecords> lstOppRecords {get; set;}
    public Map<Integer, opportunityRecords> mapOppRecords {get; set;}
    public Integer selectedRowIndex {get; set;}
    public Integer rowCount {get; set;}
    private Integer intialCount = 10;
    private Integer maxCount {get; set;}
    public List<String> lstOppName {get; set;}
    private Map<Integer, String> mapOppName {get; set;}
    private Map<Integer, String> mappedOppName = new Map<Integer, String>();
    public String dateTimeValue { get; set; }
    public Boolean showOppRec {get; set;}

/*Opportunity records*/
public class opportunityRecords implements Comparable
{
    //Holds record Index
    public Integer recIndex {get; set;}
    public String oppType {get; set;}
    public Opportunity opp {get; set;}
    public Boolean rendered {get; set;}

    public opportunityRecords(Integer index)
    {
        recIndex = index;
        opp = new Opportunity();
        rendered = true;
    }

    // Implement the compareTo() method
    public Integer compareTo(Object compareTo) {
        opportunityRecords oppRec = (opportunityRecords)compareTo;
        if (recIndex == oppRec.recIndex) return 0;
        if (recIndex > oppRec.recIndex) return 1;
        return -1;        
    }
}

////save the records by adding the elements in the inner class list to lstAcct,return to the same page
public PageReference Convert()
{
    system.debug('>>>Inside convert');
    PageReference pr = new PageReference('/' + siteObj.Id);
    Integer totalRows = 0;
    lstOpp.clear();
    for(opportunityRecords oppRec : lstOppRecords)
    {
        if(oppRec.rendered)
        {
            totalRows++;
            oppRec.opp.Name = siteObj.Name+'-'+oppRec.oppType;
            oppRec.opp.Site_Ref_No__c = siteObj.Site_Ref_No__c;
            oppRec.opp.Site_Lead__c = siteObj.Id;
            if(oppRec.opp.StageName == 'No Contact Made')
                oppRec.opp.Probability= 0;
            else if(oppRec.opp.StageName == 'Contact Made')
                oppRec.opp.Probability= 10;
            else if(oppRec.opp.StageName == 'Taking Off')
                oppRec.opp.Probability= 25;
            else if(oppRec.opp.StageName == 'Quotation with Customer ')
                oppRec.opp.Probability= 50;
            else if(oppRec.opp.StageName == 'Negotiation/Review')
                oppRec.opp.Probability= 75;
            else if(oppRec.opp.StageName == 'Closed Won')
                oppRec.opp.Probability= 100;
            else if(oppRec.opp.StageName == 'Closed Lost')
                oppRec.opp.Probability= 0;

            if (oppRec.opp.AccountId != null && oppRec.opp.CloseDate != null && oppRec.opp.OwnerId != null)
            {    /*Default user as Opp owner*/
                /*if (oppRec.opp.OwnerId == null)
                    oppRec.opp.OwnerId = UserInfo.getUserId();*/
                system.debug('>>>Check already available:');
                system.debug(oppRec.opp);
                lstOpp.add(oppRec.opp);
                //mapOppRecords.remove(oppRec.recIndex);
                oppRec.rendered = false;
                mapOppRecords.put(oppRec.recIndex,oppRec);
                rowCount = rowCount - 1;
            }
        }
    }
    insert lstOpp;
    if (lstOpp.size() != totalRows)
    {
        clearAndPopulateList();
        String successMsg = '';
        if(lstOpp.size() > 0)
        {
            if(lstOpp.size() == 1)
                successMsg = 'Successfully Created ' + lstOpp.size() + ' Opportunity';
            else if(lstOpp.size() > 1)
                successMsg = 'Successfully Created ' + lstOpp.size() + ' Opportunities';
            ApexPages.AddMessage(new ApexPages.Message(ApexPages.Severity.CONFIRM,successMsg));   
        }
        String errorMsg = 'Please enter Account,Sales Person and Close Date for below Opportunities. Otherwise click cancel to go back to Site Leads page.';

        ApexPages.AddMessage(new ApexPages.Message(ApexPages.Severity.INFO,errorMsg));

        pr = null;
    }
    else
    {
        showOppRec = false;
        ApexPages.AddMessage(new ApexPages.Message(ApexPages.Severity.CONFIRM,'All Opportunities created successfully. Please click cancel to go back to Site Leads page.')); 
        //pr.setRedirect(True);
        pr = null;
    }
    return pr;
}

//add one more row
public void Add()
{   
    if (rowCount < maxCount)
    {
        rowCount = rowCount+1;
        addMore();
        clearAndPopulateMap();
    }
    else
    {
        ApexPages.AddMessage(new ApexPages.Message(ApexPages.Severity.ERROR,'Maximum row that can be added is ' + maxCount));
        //return null;
    }
}

/*Begin addMore*/
public void addMore()
{
//clearAndPopulateMap();
    //call to the iner class constructor
    Set<Integer> setName = mapOppName.keySet();
    List<Integer> lstName = new List<Integer>();
    lstName.addAll(setName);
    mappedOppName.put(lstName[0], mapOppName.get(lstName[0]));
    mapOppName.remove(lstName[0]);
    opportunityRecords oppRecord = new opportunityRecords(rowCount);
    oppRecord.oppType = mappedOppName.get(lstName[0]);
 /*----Default value for Account and Salesperson----*/
  /*Id accId = siteObj.Account__c;
    system.debug('accId' + accId);
    if (accId != null)
    {
        oppRecord.opp.AccountId = accId;
        Id ownerid = getSalesPerson(oppRecord.opp.AccountId);
        if (ownerid != null)
            oppRecord.opp.OwnerId = ownerid;
    }*/
   // oppRecord.opp.CloseDate = siteObj.Completion_Date__c;
    oppRecord.opp.CloseDate=date.today()+7;
    oppRecord.opp.StageName = 'No Contact Made';
    //add the record to the inner class list
    lstOppRecords.add(oppRecord);
//clearAndPopulateMap();
    system.debug('lstOppRecords---->'+lstOppRecords);            
}/* end addMore*/


private void clearAndPopulateMap()
{
    if(!lstOppRecords.isEmpty())
    {
        mapOppRecords.clear();
        for(opportunityRecords oppRec : lstOppRecords)
        {
            mapOppRecords.put(oppRec.recIndex, oppRec);
        }
        lstOppRecords.sort();
    }
}

private void clearAndPopulateList()
{
    if(!lstOppRecords.isEmpty())
    {
        lstOppRecords.clear();
        lstOppRecords = mapOppRecords.values();
        lstOppRecords.sort();
    }
}

/* begin delete */
public PageReference Del()
{
    /*if(rowCount > 1)
    {
        system.debug('selected row index---->'+selectedRowIndex);
        //lstOppRecords.remove(selectedRowIndex-1);
        opportunityRecords opRec = mapOppRecords.get(selectedRowIndex);
        for(Integer i = 0; i < mapOppRecords.size(); i++)
        {
            if (mappedOppName.containsKey(i) && mappedOppName.get(i) == opRec.oppType)
            {
                mapOppName.put(i, mappedOppName.get(i));
                mappedOppName.remove(i);
                break;
            }
        }
    mapOppRecords.remove(selectedRowIndex);
        rowCount = rowCount - 1;
    clearAndPopulateList();
        return null;
    }
    else
    {
        ApexPages.AddMessage(new ApexPages.Message(ApexPages.Severity.ERROR,'Please enter atleast one Opportunity.'));
        return null;
    }*/
    return null;

} /*End del*/

private void AddOpportunity(Integer rc)
{
    for(Integer i = 0; i < rc; i++) 
    {
        rowCount += i;
        addMore();
    }
    clearAndPopulateMap();
}

//Sales Person Populate from Account
public Id getSalesPerson(Id accountid)
{
    Id salesPersonId = [select EXO_Sales_Rep__r.id, EXO_Sales_Rep__r.Name 
                    from Account 
                    where id=:accountid 
                    LIMIT 1].EXO_Sales_Rep__r.Id;
    return salesPersonId;
}

//OnChange SalesPerson Populate
public void SalesPersonPopulate()
{
    system.debug('>>>ListOpprec start ' + lstOppRecords);
    opportunityRecords opRec = mapOppRecords.get(selectedRowIndex);
    if (opRec.opp.AccountId != null)
    {
        Id ownerid = getSalesPerson(opRec.opp.AccountId);
        opRec.opp.OwnerId = ownerid;
        mapOppRecords.put(selectedRowIndex, opRec);
        clearAndPopulateList();
    }
    system.debug('>>>ListOpprec start ' + lstOppRecords);
}

private void opportunityList()
{
    lstOppName = new List<String>();
    mapOppName = new Map<Integer, String>();
    lstOppName.add('Floor Systems');
    lstOppName.add('Footings & Concrete');
    lstOppName.add('Frames');
    lstOppName.add('Roof');
    lstOppName.add('External Cladding');
    lstOppName.add('Plasterer');
    lstOppName.add('Fix out');
    lstOppName.add('Renderer');
    lstOppName.add('Retaining Walls / Landscaping');
    lstOppName.add('Hire');
    maxCount = lstOppName.size();
    for(Integer i = 0; i < maxCount; i++)
    {
        mapOppName.put(i, lstOppName[i]);
    }
}
public List<SelectOption> getItems() {
    List<SelectOption> options = new List<SelectOption>();
    for(String name : lstOppName)
    {
        options.add(new SelectOption(name,name));
    }
    return options;
}

/*Constructor*/
public Conversion_site(ApexPages.StandardController stdController)
{  dateTimeValue = System.Now().format('dd/MM/yyyy');//GMT 
    siteObj = (Site__c)stdController.getRecord();
    lstOppRecords = new List<opportunityRecords>();
    mapOppRecords = new Map<Integer, opportunityRecords>();
    opportunityList();
    rowCount = 0;
    AddOpportunity(intialCount);
    selectedRowIndex = 0;
    showOppRec = true;
}/*End Constructor*/
Laxman RaoLaxman Rao

First read the below link's and try to write the test class.

 

http://wiki.developerforce.com/page/An_Introduction_to_Apex_Code_Test_Methods