+ Start a Discussion
Peter TheodorePeter Theodore 

Test Class for Custom Controller

I've built a custom controller to handle a Chatter Publisher global action that uses a Visualforce page. I need some help writing the test class for the controller so I can deploy. Here is the code for my controller:
 
public with sharing class CreateRequestController {
    public Marketing_Request__c theRequest {get; set;}
    public String lastError {get; set;}
    public CreateRequestController() {
        theRequest = new Marketing_Request__c();
        lastError = 'error';
    }
      
    public PageReference createRequest() {
        createNewRequest();
        theRequest = new Marketing_Request__c();
        return null;
    }
       
     private void createNewRequest() {      
        try {
            insert theRequest;
            
            FeedItem post = new FeedItem();
            post.ParentId = ApexPages.currentPage().getParameters().get('id');
            post.Body = 'created a Marketing Request';
            post.type = 'LinkPost';
            post.LinkUrl = '/' + theRequest.Id;
            post.Title = 'Marketing Request For ' + theRequest.Type_of_Request__c;
            insert post;
        } catch(System.Exception ex){
           lastError = ex.getMessage();
        }
    }   
}

I've basically taken the controller code from this Salesforce reference and repurposed it: https://help.salesforce.com/HTViewHelpDoc?id=creating_vf_pages_for_custom_actions.htm

Any help would be greatly appreciated, and please let me know if you need more info.
James LoghryJames Loghry
Salesforce has plenty of documentation out there for getting started writing unit tests. Here are a few blog posts on the topic: Thankfully, you're class is pretty simple, so you shouldn't need to write many test methods to cover all the scenarios in your controller.  But the gist is that you should:
  • Create one unit test for each condition.  (E.g. a successful insert in the createNewRequest method, and a method that will cause an exception to be thrown.
  • Update some fields on the theRequest variable and use System.asserts to verify they are inserted properly.
  • Strive cover your class with 100% code coverage.
Good luck!