1

I have the below controller written and I have never had to write a test class for one of these so I am not sure how to go about it. Any thoughts?

public with sharing class sortController {
Public List<task> taskList {get;set;}
Public sortController(ApexPages.StandardController stdController){
    taskList = [SELECT OwnerId,Subject,ActivityDate,WhoId,Description FROM task order by ActivityDate desc];
}
}
1

You should work through some Trailhead modules if you're unsure of where to start. The idea behind what you have to test here is very simple, however. Insert your data, then construct your class.

You may want to test the ordering aspect, but I'd say that's a bit over the top, and you can just check how many Task records are returned by the query. I'd also make that taskList property private set. You should always do so unless you know for sure you want the page to be able to set the value.

static testMethod void testMyExtension()
{
    final Integer RECORD_COUNT = 10;

    Account record = new Account(/*required fields*/);
    insert record;

    List<Task> tasks = new List<Task>();
    for (Integer i = 0; i < RECORD_COUNT; i++)
        tasks.add(new Task(/*required fields*/));
    insert tasks;

    ApexPages.StandardController controller = new ApexPages.StandardController(record);

    Test.startTest();
        MyExtension extension = new MyExtension(controller);
    Test.stopTest();

    system.assertEquals(RECORD_COUNT, extension.tasks.size(), 'All records should be queried');
}

One more note, in terms of your naming, the class you are writing is an extension, not a controller. This post is well worth the read: Difference between controller and extensions

| improve this answer | |
  • Adrian, I am receiving an error with this. Invalid type: My Extension – cmmoutes13 Dec 15 '16 at 16:16
  • My code sample is just paraphrasing so that you can't just ingrain copy-paste programming into your habits (a very bad one, that). You need to think about what the code is doing, it should be obvious what you have to rename. @cmmoutes13 – Adrian Larson Dec 15 '16 at 16:33

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.