0

I have a simple Visualforce page with a simple controller as follows

public class EDU_CustomController_Getter {

 private String sortOrder = 'LastName';

//This is the getter method used to parse values from Apex Controller to Visualforce Page 
public List<Contact> getContacts() {

//List<Contact> results = [SELECT Id, FirstName, LastName, Title, Email FROM CONTACT ORDER BY = :sortOrder];
List<Contact> results = Database.query(
    'SELECT Id, FirstName, LastName, Title, Email ' +
    'FROM Contact ' +
    'ORDER BY ' + sortOrder + ' ASC ' +
    'LIMIT 10'
);
return results;
}

public void sortByLastName() {
    this.sortOrder = 'LastName';
}

public void sortByFirstName() {
    this.sortOrder = 'FirstName';
}
}

I have the following testclass but I'm only getting 10% code coverage. How can I cover the missing lines? Test Class as follows:

@isTest
public class test_EDU_CustomController_Getter {

static testmethod void testContactVisible(){
    Test.startTest();

    Account testAccount = new Account();
    testAccount.Name='Test Account' ;
    insert testAccount;

    Contact testcont = new Contact();
    testcont.FirstName='Test';
    testcont.LastName='Test';
    testcont.Accountid= testAccount.id;       
    insert testcont;

    PageReference myVfPage = Page.EDU_GetterMethods;
    Test.setCurrentPage(myVfPage); 

    //construct controller
    EDU_CustomController_Getter controller = new EDU_CustomController_Getter();
    String sortOrder = 'LastName';

    //Test query
    List<Contact> Records = Database.query(
    'SELECT Id, FirstName, LastName, Title, Email ' +
    'FROM Contact ' +
    'ORDER BY ' + sortOrder + ' ASC ' +
    'LIMIT 10'
);

    Test.stoptest();  
}
}
0

You need to call the methods in your controller. The point of a unit test is not to duplicate the code, but actually test the code you're trying to cover. Note that proper testing of your code will involve at least 2 contacts to make sure the records are sorted correctly.

EDU_CustomController_Getter controller = new EDU_CustomController_Getter();
Contact[] records = controller.getRecords();
System.assertEquals(2, records.size(), 'Expected two contacts.');
controller.sortByFirstName();
records = controller.getRecords();
System.assertEquals('Test1', records[0].LastName, 'Expected Test1 to appear first.');
// ... etc ...

This code above is only for example; you will need to make the appropriate changes to properly test your code.

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.