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
Oleg NikitchukOleg Nikitchuk 

How to test my Apex custom controller?

Hi everyone!

I am new to SF and Apex. Started from administration and now struggling with the coding. I had some little knowledge of HTML,CSS,JS and Java but honestly it's not much. 

So, I need to write tests for my Apex custom controller. i'll show what I have, this is my VF page:
User-added image
It shows positions and their status. I can change status with the status button and save them. Also, I can use filter drop down list. It's not much of functionallity there. So, right now I have a task to write tests for my Apex custom controller. Honestly, I have no idea how to do it as I've never writter tests before. Need some help or ideas here. 

Here's my VF page code:
<apex:page controller="MyPositionsController" showHeader="true" sidebar="true">
<apex:form>
<apex:pageBlock title="Positions list">
<apex:outputLabel value="View: "></apex:outputLabel>
<apex:selectList value="{!filterId}" size="1">
<apex:actionSupport event="onchange" action="{!processRequests}" rerender="positions_table"/>
<apex:selectOptions value="{!items}"/>
</apex:selectList>
<apex:pageBlockTable value="{!results}" var="pos" rows="20" id="positions_table">
<apex:column value="{!pos.Name}"></apex:column>
<apex:column headerValue="Status">
<apex:inputField value="{!pos.Status__c}"></apex:inputField>
</apex:column>
<apex:column value="{!pos.Opening_date__c}"></apex:column>
<apex:column value="{!pos.Closing_date__c}"></apex:column>
<apex:column value="{!pos.Salary_max__c}"></apex:column>
<apex:column value="{!pos.Salary_min__c}"></apex:column> -->
</apex:pageBlockTable>
<apex:pageMessages id="showmsg"></apex:pageMessages>
<apex:pageBlockButtons location="top">
<apex:commandButton value="Save" action="{!save}" reRender="showmsg"></apex:commandButton>
</apex:pageBlockButtons>
</apex:pageBlock>
</apex:form>
</apex:page>

Apex class:
public with sharing class MyPositionsController {
public List<Position__c> results {get;set;}
public String filterId {get;set;}
public MyPositionsController(){
init();
}
public void init(){
results = [SELECT Name,Status__c,Opening_date__c,Closing_date__c,Salary_max__c,Salary_min__c FROM Position__c ORDER BY Status__c LIMIT 25];
}
public SelectOption[] processRequests(){
if (filterId == 'All') {
results = [SELECT Name,Status__c,Opening_date__c,Closing_date__c,Salary_max__c,Salary_min__c FROM Position__c WHERE Status__c != null ORDER BY Name LIMIT 25];
} else{
results = [SELECT Name,Status__c,Opening_date__c,Closing_date__c,Salary_max__c,Salary_min__c FROM Position__c WHERE Status__c = :filterId ORDER BY Name LIMIT 25];
}
return null;
}
public List<SelectOption> getItems(){
List<SelectOption> options = new List<SelectOption>();
Schema.DescribeFieldResult fieldResult = Position__c.Status__c.getDescribe();
List<Schema.PicklistEntry> ple = fieldResult.getPicklistValues();
options.add(new SelectOption('All','All'));
for (Schema.PicklistEntry f : ple) {
options.add(new SelectOption(f.getLabel(),f.getValue()));
}
return options;
}
public void save(){
update results;
ApexPages.Message myMsg = new ApexPages.Message(ApexPages.Severity.CONFIRM,'Successfully saved!');
ApexPages.addMessage(myMsg);
init();
}
}

As far as I understand from documentation, I need at least 75% test coverage. But I want to test all methods there as well as constructor method(I guess with constroctor, I need to use List.size method or something like that in order to test it). I don't want the solution, a hint or a few hint will do the work.

Thanks in advance!
Best Answer chosen by Oleg Nikitchuk
Suraj Tripathi 47Suraj Tripathi 47
Hi Oleg,

Thanks for your reply,You can take reference from this below code.
@isTest
public class MyPositionsController_Test {
    @testSetup
    static void testMethod1(){
        test.startTest();
        Position__c pos = new Position__c();
        pos.Status__c='status';
        pos.Opening_date__c=date.today();
        pos.Closing_date__c=date.today().addDays(30);
        pos.Salary_max__c=20000;
        pos.Salary_min__c=10000;
        insert pos;
        System.assert(pos.Id!=null);
        test.stopTest();
    }
    
    @isTest
    static void MyPositionsController_Test(){
        Position__c pos=[select id,Status__c,Opening_date__c,Closing_date__c,Salary_max__c,Salary_min__c from Position__c LIMIT 1];
        test.startTest();
        MyPositionsController posController = new MyPositionsController();
        test.stopTest();
        System.assertEquals('status',pos.Status__c);
    }
    
    @isTest
    static void processRequests_Test(){
        Position__c pos=[select id,Status__c,Opening_date__c,Closing_date__c,Salary_max__c,Salary_min__c from Position__c LIMIT 1];
        test.startTest();
        MyPositionsController posController = new MyPositionsController();
        posController.filterId='ALL';
        posController.processRequests();
        test.stopTest();
        System.assertEquals('ALL',posController.filterId);
    }
    
    @isTest
    static void processRequests1_Test(){
        Position__c pos=[select id,Status__c,Opening_date__c,Closing_date__c,Salary_max__c,Salary_min__c from Position__c LIMIT 1];
        test.startTest();
        MyPositionsController posController = new MyPositionsController();
        posController.processRequests();
        test.stopTest();
        System.assertEquals(null,posController.filterId);
    }
    
    @isTest
    static void getItems_Test(){
        Position__c pos=[select id,Status__c,Opening_date__c,Closing_date__c,Salary_max__c,Salary_min__c from Position__c LIMIT 1];
        test.startTest();
        MyPositionsController posController = new MyPositionsController();
        posController.getItems();
        test.stopTest();
        System.assertEquals('status',pos.Status__c);
        
    }
    
    @isTest
    static void save_Test(){
        test.startTest();
        MyPositionsController posController = new MyPositionsController();
        posController.save();
        test.stopTest();
    }
}

You mentioned above that i add 2 more things. Maybe this test class is like as you said.
In case you find any other issue please mention.
If you find your Solution then mark this as the best answer. 

Thanks and Regards
Suraj Tripathi.

All Answers

Suraj Tripathi 47Suraj Tripathi 47
Hi Oleg Nikitchuk,

Please check this Test class:-
@isTest
public class MyPositionsController_Test {
    static testMethod void test(){
        Position__c pos = new Position__c();
        pos.Status__c='status';
        pos.Opening_date__c=date.today();
        pos.Closing_date__c=date.today().addDays(30);
        pos.Salary_max__c=20000;
        pos.Salary_min__c=10000;
        insert pos;
        
        MyPositionsController myPosCon = new MyPositionsController();
        myPosCon.processRequests();
        myPosCon.getItems();
        myPosCon.save();
        
        myPosCon.filterId='All';
        myPosCon.processRequests();
    }
}

Please Mark it as Best Answer if it helps.
Thanks
Oleg NikitchukOleg Nikitchuk
Hi Suraj, 

Thanks for your reply. Is there a way to use Test.startTest() and Test.stopTest() with this code?
Suraj Tripathi 47Suraj Tripathi 47
Hi Oleg,
Yes you can do that, here i have written testMethod but instead of that you can write test.startTest and test.stopTest. Both are same 
 
@isTest
public class MyPositionsController_Test {
    static testMethod void test(){
        Position__c pos = new Position__c();
        pos.Status__c='status';
        pos.Opening_date__c=date.today();
        pos.Closing_date__c=date.today().addDays(30);
        pos.Salary_max__c=20000;
        pos.Salary_min__c=10000;
        insert pos;
        
        MyPositionsController myPosCon = new MyPositionsController();
        myPosCon.processRequests();
        myPosCon.getItems();
        myPosCon.save();
        
        myPosCon.filterId='All';
        myPosCon.processRequests();
    }
}


or

//2nd method
@isTest
public class MyPositionsController_Test {
    @isTest static void test(){
        Position__c pos = new Position__c();
        pos.Status__c='status';
        pos.Opening_date__c=date.today();
        pos.Closing_date__c=date.today().addDays(30);
        pos.Salary_max__c=20000;
        pos.Salary_min__c=10000;
        insert pos;
        test.startTest();
        MyPositionsController myPosCon = new MyPositionsController();
        myPosCon.processRequests();
        myPosCon.getItems();
        myPosCon.save();
        
        myPosCon.filterId='All';
        myPosCon.processRequests();
        Test.stopTest();
    }
}

Please Mark it as Best Answer if it helps.
Thanks
Oleg NikitchukOleg Nikitchuk
Thanks for your reply, Suraj.

Also, I am thinking to add 2 more things:
1) After insert pos I want to use an example from official documentaion, maybe something like this: 
for(Position__c pos:[SELECT Status__c FROM Position__c
WHERE ...
}
2) and then use System.AssertEquals.
I dunno, this is just what I intend to do with my code. Not sure if it's applicable here, please advice.
Oleg NikitchukOleg Nikitchuk
I mean this test method should have some logic like we compare some result with expected result.
Suraj Tripathi 47Suraj Tripathi 47
Hi Oleg,

Thanks for your reply,You can take reference from this below code.
@isTest
public class MyPositionsController_Test {
    @testSetup
    static void testMethod1(){
        test.startTest();
        Position__c pos = new Position__c();
        pos.Status__c='status';
        pos.Opening_date__c=date.today();
        pos.Closing_date__c=date.today().addDays(30);
        pos.Salary_max__c=20000;
        pos.Salary_min__c=10000;
        insert pos;
        System.assert(pos.Id!=null);
        test.stopTest();
    }
    
    @isTest
    static void MyPositionsController_Test(){
        Position__c pos=[select id,Status__c,Opening_date__c,Closing_date__c,Salary_max__c,Salary_min__c from Position__c LIMIT 1];
        test.startTest();
        MyPositionsController posController = new MyPositionsController();
        test.stopTest();
        System.assertEquals('status',pos.Status__c);
    }
    
    @isTest
    static void processRequests_Test(){
        Position__c pos=[select id,Status__c,Opening_date__c,Closing_date__c,Salary_max__c,Salary_min__c from Position__c LIMIT 1];
        test.startTest();
        MyPositionsController posController = new MyPositionsController();
        posController.filterId='ALL';
        posController.processRequests();
        test.stopTest();
        System.assertEquals('ALL',posController.filterId);
    }
    
    @isTest
    static void processRequests1_Test(){
        Position__c pos=[select id,Status__c,Opening_date__c,Closing_date__c,Salary_max__c,Salary_min__c from Position__c LIMIT 1];
        test.startTest();
        MyPositionsController posController = new MyPositionsController();
        posController.processRequests();
        test.stopTest();
        System.assertEquals(null,posController.filterId);
    }
    
    @isTest
    static void getItems_Test(){
        Position__c pos=[select id,Status__c,Opening_date__c,Closing_date__c,Salary_max__c,Salary_min__c from Position__c LIMIT 1];
        test.startTest();
        MyPositionsController posController = new MyPositionsController();
        posController.getItems();
        test.stopTest();
        System.assertEquals('status',pos.Status__c);
        
    }
    
    @isTest
    static void save_Test(){
        test.startTest();
        MyPositionsController posController = new MyPositionsController();
        posController.save();
        test.stopTest();
    }
}

You mentioned above that i add 2 more things. Maybe this test class is like as you said.
In case you find any other issue please mention.
If you find your Solution then mark this as the best answer. 

Thanks and Regards
Suraj Tripathi.
This was selected as the best answer