2

I have created a custom extension which allows me to pull specified data into my visualforce news page. In my extension I have mutliple queries which pull filtered data if used with url parameters and also have my own pagination built in.

Extension:

public with sharing class force_NewsController {

    public force_NewsController (){
        CountTotalRecords= [SELECT COUNT() FROM News__c];

        // pagination filter
        String category = Apexpages.currentPage().getParameters().get('cat');
        if (category == 'product launches') {
            CountTotalRecords = [SELECT COUNT() FROM News__c WHERE Category__c = 'Product Launches'];
        } else if (category == 'events') {
            CountTotalRecords = [SELECT COUNT() FROM News__c WHERE Category__c = 'Events'];
        } else if (category == 'press releases') {
            CountTotalRecords = [SELECT COUNT() FROM News__c WHERE Category__c = 'Press Releases'];
        } else if (category == 'case studies') {
            CountTotalRecords = [SELECT COUNT() FROM News__c WHERE Category__c = 'Case Studies'];
        } else {
            CountTotalRecords = [SELECT COUNT() FROM News__c];
        }
    }

    public Integer CountTotalRecords{get;set;}
    public String QueryString {get;set;}
    public Integer OffsetSize = 0;
    private Integer QueryLimit = 6;
    public string excerpt;
    public list<News__c> lstItem {get;set;}
    public list<News__c> NewsList {get;set;}
    public list<News__c> EventList {get;set;}
    public map<id,string> newsmap{get;set;}

    public list<News__c> getNewsItems(){
        lstItem = new list<News__c>();

        String category = Apexpages.currentPage().getParameters().get('cat');
        String query = 'SELECT Id, Name, Title__C, Content__c, Publish_Date__c, Category__c, Event_Date_Start__c, Event_Date_End__c, Event_Location__c, ';
        query += '(Select Id, Name, LastModifiedDate From Attachments Order By LastModifiedDate DESC) ';
        query += 'FROM News__c ';

        if (category != null)
        {
            query += 'WHERE Category__c = :category ';
        }

        query += 'ORDER BY Publish_Date__c DESC, Name DESC LIMIT :QueryLimit OFFSET :OffsetSize';

        lstItem = Database.query(query);
        return lstItem;
    }

    public Boolean getDisablePrevious(){
        if(OffsetSize>0){
            return false;
        }
        else return true;
    }

    public Boolean getDisableNext() {
        if (OffsetSize + QueryLimit < countTotalRecords){
            return false;
        }
        else return true;
    }

    public PageReference Next() {
        OffsetSize += QueryLimit;
        return null;
    }

    public PageReference Previous() {
        OffsetSize -= QueryLimit;
        return null;
    }

    public list<News__c> getHomeNewsItems(){
        NewsList = new list<News__c>();

        String query = 'SELECT Id, Name, Title__C, Content__c, Publish_Date__c, Category__c, ';
        query += '(Select Id, Name, LastModifiedDate From Attachments Order By LastModifiedDate DESC) ';
        query += 'FROM News__c ';
        query += 'WHERE Category__c != \'Events\' ';
        query += 'ORDER BY Publish_Date__c DESC, Name DESC LIMIT 5';

        NewsList = Database.query(query);
        return NewsList;
    }

    public list<News__c> getUpcomingEvents(){
        EventList = new list<News__c>();

        String query = 'SELECT Id, Name, Title__C, Publish_Date__c, Event_Date_Start__c, Event_Date_End__c, Event_Location__c ';
        query += 'FROM News__c ';
        query += 'WHERE Category__c = \'Events\' ';
        query += 'ORDER BY Event_Date_Start__c ASC, Name DESC LIMIT 3';

        EventList = Database.query(query);
        return EventList;
    }

    public LIST<Service_Status__c> getServiceItems() {
        return [SELECT Id, Name, Information__c, Status_Colour__c FROM Service_Status__c ORDER BY Priority__c DESC];
    }

    public LIST<News__c> getAlerts() {
        date d = system.today().addDays(-8);
        return [SELECT Id, Name, Title__C, Publish_Date__c FROM News__c WHERE Flash_Message__c = TRUE AND Publish_Date__c > :d  ORDER BY Publish_Date__c DESC LIMIT 1];
    }

}

* SECOND UPDATE*

I have got 79% coverage so far :D
Could someone show me how I can test the pagination methods to get 100% coverage. The following methods still need code coverage:

  • getDisablePrevious()
  • getDisableNext()
  • Next()
  • Previous()

Test Class:

@isTest
private class test_NewsController {

    static testMethod void NewsItemsTest() {

        News__c n = new News__c();
        n.Title__c = 'Test Title';
        n.Publish_Date__c = system.today();
        n.Category__c = 'Press Releases';
        n.Content__c = 'Sample text goes here';
        insert n;

        PageReference pageRef = Page.force_NewsArchive;
        Test.setCurrentPage(pageRef);
        ApexPages.Standardcontroller sc = new ApexPages.Standardcontroller(n);

        force_NewsController nc = new force_NewsController();
        list<News__c> news = nc.getNewsItems();
        System.assertEquals(1, news.size());

    }

    static testMethod void HomepageNewsTest() {

        News__c n = new News__c();
        n.Title__c = 'Test Title';
        n.Publish_Date__c = system.today();
        n.Category__c = 'Press Releases';
        n.Content__c = 'Sample text goes here';
        insert n;

        News__c n2 = new News__c();
        n2.Title__c = 'Test Event';
        n2.Publish_Date__c = system.today();
        n2.Category__c = 'Events';
        n2.Content__c = 'Sample text for event goes here';
        n2.Event_Date_Start__c = system.today();
        n2.Event_Date_End__c = system.today();
        n2.Event_Location__c = 'Compass Centre';
        insert n2;

        PageReference pageRef = Page.force_NewsArchive;
        Test.setCurrentPage(pageRef);
        ApexPages.Standardcontroller sc = new ApexPages.Standardcontroller(n);

        force_NewsController nc = new force_NewsController();
        list<News__c> news = nc.getHomeNewsItems();
        System.assertEquals(1, news.size());

    }

    static testMethod void NewsArchiveFilterTest() {

        News__c n = new News__c();
        n.Title__c = 'Test Title';
        n.Publish_Date__c = system.today();
        n.Category__c = 'Press Releases';
        n.Content__c = 'Sample text goes here';
        insert n;

        News__c n2 = new News__c();
        n2.Title__c = 'Test Event';
        n2.Publish_Date__c = system.today();
        n2.Category__c = 'Events';
        n2.Content__c = 'Sample text for event goes here';
        n2.Event_Date_Start__c = system.today();
        n2.Event_Date_End__c = system.today();
        n2.Event_Location__c = 'Compass Centre';
        insert n2;

        News__c n3 = new News__c();
        n3.Title__c = 'Test Case Study';
        n3.Publish_Date__c = system.today();
        n3.Category__c = 'Case Studies';
        n3.Content__c = 'Sample text goes here';
        insert n3;

        News__c n4 = new News__c();
        n4.Title__c = 'Test Product Launch';
        n4.Publish_Date__c = system.today();
        n4.Category__c = 'Product Launches';
        n4.Content__c = 'Sample text goes here';
        insert n4;

        News__c n5 = new News__c();
        n5.Title__c = 'Test Incident Update';
        n5.Publish_Date__c = system.today();
        n5.Category__c = 'Incident Updates';
        n5.Content__c = 'Sample text goes here';
        insert n5;

        PageReference pageRef = Page.force_NewsArchive;
        Test.setCurrentPage(pageRef);
        ApexPages.Standardcontroller sc = new ApexPages.Standardcontroller(n);
        ApexPages.currentPage().getParameters().put('cat', 'Events');

        force_NewsController nc = new force_NewsController();
        list<News__c> news = nc.getNewsItems();
        System.assertEquals(1, news.size());

        // SECOND TEST
        ApexPages.Standardcontroller sc2 = new ApexPages.Standardcontroller(n);
        ApexPages.currentPage().getParameters().put('cat', 'Case Studies');

        force_NewsController nc2 = new force_NewsController();
        list<News__c> news2 = nc2.getNewsItems();
        System.assertEquals(1, news2.size());

        // THIRD TEST
        ApexPages.Standardcontroller sc3 = new ApexPages.Standardcontroller(n);
        ApexPages.currentPage().getParameters().put('cat', 'Press Releases');

        force_NewsController nc3 = new force_NewsController();
        list<News__c> news3 = nc3.getNewsItems();
        System.assertEquals(1, news3.size());

        // FOURTH TEST
        ApexPages.Standardcontroller sc4 = new ApexPages.Standardcontroller(n);
        ApexPages.currentPage().getParameters().put('cat', 'Product Launches');

        force_NewsController nc4 = new force_NewsController();
        list<News__c> news4 = nc4.getNewsItems();
        System.assertEquals(1, news4.size());

        // FIFTH TEST
        ApexPages.Standardcontroller sc5 = new ApexPages.Standardcontroller(n);
        ApexPages.currentPage().getParameters().put('cat', 'Incident Updates');

        force_NewsController nc5 = new force_NewsController();
        list<News__c> news5 = nc5.getNewsItems();
        System.assertEquals(1, news5.size());

    }

    static testMethod void UpcomingEventsTest() {

        News__c n = new News__c();
        n.Title__c = 'Test Event';
        n.Publish_Date__c = system.today();
        n.Category__c = 'Events';
        n.Content__c = 'Sample text for event goes here';
        n.Event_Date_Start__c = system.today();
        n.Event_Date_End__c = system.today();
        n.Event_Location__c = 'Compass Centre';
        insert n;

        PageReference pageRef = Page.force_Homepage;
        Test.setCurrentPage(pageRef);
        ApexPages.Standardcontroller sc = new ApexPages.Standardcontroller(n);

        force_NewsController nc = new force_NewsController();
        list<News__c> events = nc.getUpcomingEvents();
        System.assertEquals(1, events.size());

    }

    static testMethod void ServiceItemsTest() {

        Service_Status__c ss = new Service_Status__c();
        ss.Name = 'Phones';
        ss.Priority__c = 1;
        ss.Status_Colour__c = 'green';
        insert ss;

        PageReference pageRef = Page.force_Homepage;
        Test.setCurrentPage(pageRef);
        ApexPages.Standardcontroller sc = new ApexPages.Standardcontroller(ss);

        force_NewsController nc = new force_NewsController();
        list<Service_Status__c> serviceitems = nc.getServiceItems();
        System.assertEquals(1, serviceitems.size());

    }

    static testMethod void AlertTest() {

        News__c n = new News__c();
        n.Title__c = 'Test Alert';
        n.Publish_Date__c = system.today();
        n.Category__c = 'Incident Updates';
        n.Content__c = 'Sample text for event goes here';
        n.Flash_Message__c = true;
        insert n;

        PageReference pageRef = Page.force_Homepage;
        Test.setCurrentPage(pageRef);
        ApexPages.Standardcontroller sc = new ApexPages.Standardcontroller(n);

        force_NewsController nc = new force_NewsController();
        list<News__c> events = nc.getAlerts();
        System.assertEquals(1, events.size());

    }


}

UPDATE 2:
I have attempted some test methods after Mihai's response, however the second test fails, the test returns true instead of false (as expected). Am I using the variables correctly?

static testMethod void getDisablePrevious_WhenOffsetSizeEquals0_ReturnTrue(){
    boolean valueExpected;
    force_NewsController nc = new force_NewsController();
    test.startTest();
        valueExpected = nc.getDisablePrevious();
    test.stopTest();   
    System.assertEquals(true, valueExpected);
}

static testMethod void getDisablePrevious_WhenOffsetSizeEquals6_ReturnFalse(){
    boolean valueExpected;
    Integer OffsetSize = 1;
    Integer QueryLimit = 1;
    force_NewsController nc = new force_NewsController();
    test.startTest();
        valueExpected = nc.getDisablePrevious();
    test.stopTest();   
    System.assertEquals(false, valueExpected);
}
4
  • 1
    What have you tried so far? A search of google or here on SFSE will yield many results on how to write test classes. If you show a little effort and ask specific questions when you get stuff you are more likely to get a response. Asking for code to be written for you is frowned upon on SFSE and you will most likely NOT get a response
    – Eric
    Dec 23, 2014 at 17:17
  • @Eric My applogies, I was not aware of this. Creating test classes are still new to me, I understand how to create them for trigger but not for extensions that retrieve data (i.e. from SOQL statements like the one above). If you can post some relevant links to resources that would help directly with this piece of code I would be grateful. Jan 2, 2015 at 14:46
  • 1
    getNewsItems is a method not a variable, you have to open and close brackets like this getNewsItems() Jan 5, 2015 at 14:28
  • 2
    You need to set nc.OffsetSize, not OffsetSize: Integer nc.OffsetSize = 1; instead of Integer OffsetSize = 1; - Same goes for QueryLimit. Make sure you put both below force_NewsController nc = new force_NewsController(); Jan 6, 2015 at 12:07

2 Answers 2

6

When writing unit tests for controller extension and custom controller classes, you can set query parameters that can then be used in the tests.

Here is an example test class for testing an Apex extension:

@isTest

public class thecontrollerTests {

    public static testMethod void testMyController() {
        PageReference pageRef = Page.success;
        Test.setCurrentPage(pageRef);

        thecontroller controller = new thecontroller();
        String nextPage = controller.save().getUrl();

        // Verify that page fails without parameters
        System.assertEquals('/apex/failure?error=noParam', nextPage);

        // Add parameters to page URL
        ApexPages.currentPage().getParameters().put('qp', 'yyyy');

        // Instantiate a new controller with all parameters in the page
        controller = new thecontroller(); 
        controller.setLastName('lastname');
        controller.setFirstName('firstname');
        controller.setCompany('acme');
        controller.setEmail('firstlast@acme.com');
        nextPage = controller.save().getUrl();

        // Verify that the success page displays
        System.assertEquals('/apex/success', nextPage);
        Lead[] leads = [select id, email from lead where Company = 'acme'];
        System.assertEquals('firstlast@acme.com', leads[0].email);
    }
}

Please have a look at the following documentation: https://www.salesforce.com/docs/developer/pages/Content/pages_controller_error_handling.htm

Update:

Here's an example on how to test certain output:

To get code coverage for the EmployeeController you need to call the constructor and methods from the test case.

PageReference pageRef = Page.Employee_Pages;
Test.setCurrentPage(pageRef);
ApexPages.Standardcontroller sc = new ApexPages.Standardcontroller(emp);
ApexPages.currentPage().getParameters().put('Id',emp.id);

EmployeeController ec = new EmployeeController(sc);

Then you can call some of the properties to get code coverage for them as well. Make some assertions based on what you setup in the start of the test case.

list<Employee__c> emps = ec.emp;
System.assertEquals(1, emps.size();

list<Project_Experience__c> projs = ec.proj;
System.assertEquals(1, projs.size();

See for more information: need help with test class with ApexPages.currentPage().getParameters().id

6
  • Am I correct that the code and link provided relates to only testing forms and their INPUT? The apex I need to test does not belong to any forms and are simply GET requests. There are two methods which may take URL parameters but again no form data is saved. How can I use the information provided to test output data? Jan 5, 2015 at 10:29
  • 1
    Does my update answer your question? Jan 5, 2015 at 10:56
  • I think its definetly along the right track, I have updated my post.. could you please have a look? Jan 5, 2015 at 14:26
  • 1
    Try replacing nc.getNewsItems; with nc.getNewsItems(); - It's a method, not a variable. :-) Jan 5, 2015 at 14:28
  • I really appreciate your help... I have 4 methods that I need to test, they are used in conjuction with other methods for pagination. Could you point me in the right direction on how to test these? Thanks in advance :D Jan 5, 2015 at 15:49
2
+50

In response to how to test your remaining test methods:

  • getDisablePrevious()
  • getDisableNext()
  • Next()
  • Previous()

You should just be able to call them in your test method, so you would have something like this:

static testMethod void testNextMethod {
       force_NewsController nc = new force_NewsController();
       System.assert(nc.Next() == null);
}

You have to do the same for the Previous() method. See the documentation here

For the other two methods you have to create these unit tests:

static testMethod void getDisablePrevious_WhenOffsetSizeEquals0_ReturnFalse(){
       boolean valueExpected;
       force_NewsController nc = new force_NewsController();
       test.startTest();
             valueExpected = nc.getDisablePrevious();
       test.stopTest();   
       System.assertEquals(false, valueExpected);
}

It's also important to name your unit tests right and have a naming convention so other in the future will know what you are testing for. Here is a great article by Roy Osherove on the naming convention.

You will have 3 more unit tests to create, one because you have to test when getDisablePrevious() returns true and when getDisableNext() method returns true or false. You have to set the variables in your unit test OffsetSize, QueryLimit and countTotalRecords so it will take the test through the various parts of the if/else code.

UPDATE

static testMethod void getDisablePrevious_WhenOffsetSizeEquals6_ReturnFalse(){
           boolean valueExpected;
           force_NewsController nc = new force_NewsController();
           nc.OffsetSize = 6; 
           test.startTest();
                 valueExpected = nc.getDisablePrevious();
           test.stopTest();   
           System.assertEquals(true, valueExpected);
}

Pay attention to your code and how to get the code to execute the various paths. And also pay attention to what you are trying to test because you are saying in the test name that you setting the variable to 6 but you were setting it to 1.

The variables that you are trying to set are in the controller so only after you instantiate the controller that's when you set the variables. The variables will only be instantiated when the you instantiate the controller. Have look here

Instance methods, member variables, and initialization code are associated with a particular object and have no definition modifier. When you declare instance methods, member variables, or initialization code, an instance of that item is created with every object instantiated from the class.

2
  • Thanks Mihai for your response, could you check my updated post please Jan 6, 2015 at 11:48
  • Updated my answer Jan 6, 2015 at 12:37

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.