2

I have a custom controller with a couple of class methods I'd like to test, one of these class methods is a remote action:

global with sharing class MyCustomController {

 public class MyCustomController(){
        //constructor
        ...
        ...
  }

    @RemoteAction
    public static Boolean shareObject(string objectId){
        ...
        ...
    }

    public Map<String, String> getFieldsForSelectedObject(String searchObject){    
        ...
        ...
    }
}

Can someone point me in the right direction regarding the proper way to test these methods? Should I just plan to do it like black-box style and pass in an input and test the output is what would be expected?

1 Answer 1

4

Here is a skeleton of what your tests should look like:

@IsTest
class MyCustomControllerTests
{
    // Method stubs below
}

Testing Your Constructor

static testMethod void testConstructor()
{
    // If you do complex setup in your constructor test it here.
    // Otherwise a constructor test is likely unnecessary.
}

Testing Your Remote Action

static testMethod void testShareObject_PositiveCase()
{
    // Set up data so you will get back true

    Test.startTest();
        Boolean result = MyCustomController.shareObject(someInput);
    Test.stopTest();

    system.assertEquals(true, result, 'Explanatory message here');
}
static testMethod void testShareObject_NegativeCase()
{
    // Set up data so you will get back false

    Test.startTest();
        Boolean result = MyCustomController.shareObject(someInput);
    Test.stopTest();

    system.assertEquals(false, result, 'Explanatory message here');
}

Testing Your Map Method

static testMethod void testGetFieldsForSelectedObject()
{
    // You should really rewrite this method 
    // so its parameter type is SObjectType instead of String.

    // It also seems like it should not be dependent on any controller state
    // in which case you should make the method static.

    // Set up data
    MyCustomController controller = new MyCustomController();

    Test.startTest();
        Map<String, String> data = controller.getFieldsForSelectedObject('MyObject__c');
    Test.stopTest();

    system.assertNotEquals(null, data, 'Explanatory message here');
    system.assertEquals(expectedSize, data.size(), 'Explanatory message here');
    // Any other prudent assertions here
}
1
  • 1
    Adrian, wouldn't it be MyCustomController.shareObject() instead? Commented Jul 11, 2016 at 19:43

You must log in to answer this question.

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