1

The following method has no code coverage because it's only called from a VF page. How to call it in my test class and how to set the variables for the If() statements to be covered?

public PageReference addTraining() {
    if (currentQ.Selected_Contacts_Ids_List__c == Null || currentQ.Selected_Contacts_Ids_List__c == '') {
        List < training__c > rd = [Select ID FROM training__c WHERE Training_Resource__c =: currentQ.Id];
        delete rd;
        return null;
    }
    Training__c[] ts = new Training__c[] {};
    if (currentQ.Selected_Contacts_Ids_List__c.containsNone(',')) {
        ts.add(new Training__c(Shal__c = currentContacts_CSV, Training_Resource__c = currentQ.Id));
    } else {
        for (String cId: splitContactIds) {
            ts.add(new Training__c(Shal__c = cId, Training_Resource__c = currentQ.Id));
        }
    }
    List < training__c > rd = [Select ID FROM training__c WHERE Training_Resource__c =: currentQ.Id];
    delete rd;
    insert ts;
    init();
    return null;
}

3 Answers 3

2

You can initialize your controller class by doing

MyVisualforceController ctrl = new MyVisualforceController();

Now you can assign values to any properties you need in the method you want to test.

ctrl.currentQ = new Object();

After every dependency of your function is initialized you call your function. Use the startTest and stopTest methods to validate how close the code is to reaching governor limits.

Test.StartTest();
PageReference ref = ctrl.addTraining();
Test.StopTest();

Finally assert that the function has done what you designed it to do.

2

Simply create the instance of your class i.e

MyVisualforceController objMyVisualforceController = new MyVisualforceController();

And then by using instance of the class call to that method i.eobjMyVisualforceController.addTraining();

1

Try the below steps in your Test class.

ApexPages.standardController sc = new ApexPages.standardController();
//You can pass variables through this one like new ApexPages.StandardController(PassID);
ApexControllerCls acc= new ApexControllerCls(sc);
//ApexControllerCls is your Controller Class Calling from VF Page
acc.YOURMETHODINCLASS();

Hope this might helps....

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .