Activity Forums Salesforce® Discussions How to write test method for wrapper class?

  • Vikas Kumar

    Member
    February 8, 2017 at 12:24 pm

    Hello sushant,

    you can do something like this

    Apex Class:

    public class EmployeeController {
    public static void assignSequence(List<Employee__c> listEmployee, Decimal startNum) {
    Decimal initial = startNum;
    List<EmployeeWrapper> listEmployeeWrapper = new List<EmployeeWrapper>();

    for(Employee__c emp : listEmployee) {
    listEmployeeWrapper.add(new EmployeeWrapper(emp));
    }

    listEmployeeWrapper.sort();
    listEmployee.clear();

    for(EmployeeWrapper empW : listEmployeeWrapper) {
    listEmployee.add(empW.dirPagination);
    }

    for(Employee__c emp : listEmployee) {
    emp.Sequence_in_Section__c = initial;
    initial = initial + 10;
    }

    update listEmployee;
    }

    public class EmployeeWrapper implements Comparable {

    public Employee__c emp = new Employee__c();

    // Constructor
    public EmployeeWrapper(Employee__c empRecord) {
    emp = empRecord;
    }

    // Compare emp based on the Employee__c Age__c.
    public Integer compareTo(Object compareTo) {
    // Cast argument to EmployeeWrapper
    EmployeeWrapper compareToEmp = (EmployeeWrapper)compareTo;

    // The return value of 0 indicates that both elements are equal.
    Integer returnValue = 0;
    if (emp.Age__c > compareToEmp.emp.Age__c) {
    // Set return value to a positive value.
    returnValue = 1;
    } else if (emp.Directory_Heading__c < compareToEmp.emp.Age__c) {
    // Set return value to a negative value.
    returnValue = -1;
    }

    return returnValue;
    }
    }
    }

    Test Class:

    private class EmployeeControllerTest {
    static testMethod void empTest() {
    Employee__c emp = new Employee__c(Name = 'Test', Age__c = 12);
    EmployeeController.EmployeeWrapper empW = new EmployeeController.EmployeeWrapper(emp); //Covering inner/wrapper class
    empW.compareTo(empW);
    //Covering compareTo()
    }
    }

    Hope it may help

Log In to reply.

Popular Salesforce Blogs

Popular Salesforce Videos