3
votes

I'm currently learning apex (using the Force.com IDE), and I'm running into some trouble when writing a test for a custom controller.

The controller class is as follows:

public with sharing class CustomController {
    private List<TestObject__c> objects;

    public CustomController() {
        objects = [SELECT id, name FROM TestObject__c];
    }

    public List<TestObject__c> getObjects() {
        return objects;
    }
}

and the test class is:

@isTest
private class ControllerTest {
    static testMethod void customControllerTest() {
        CustomController controller = new CustomController();

        System.assertNotEquals(controller, null);

        List<TestObject__c> objects;

        objects = controller.getObjects();

        System.assertNotEquals(objects, null);    
    }
}

On the objects = controller.getObjects(); line I'm getting an error which says:

Save error: Method does not exist or incorrect signature: [CustomController].getObjects()

Anyone have an idea as to why I'm getting this error?

1
Did the first class definitely save ok? Can't see anything that stands out in this, generally when I see that message it's because I've done something silly, for example I've tried to call a static method but never actually used the static keyword! - Matt Lacey
For what it's worth, pasting the class into Execute Anonymous (but using Contact instead of TestObject__c) and then calling getObjects on a new instance of it works without error. - Matt Lacey
I didn't get any other errors in the code. The file saved locally, but not on the server (probably due to the test not having passed). I also get the exact same message when trying it in Execute Anonymous. - Apexer
Are you working directly against production or in a sandbox? It won't run the tests saving to sandbox and so it shouldn't only be saved locally. I'm assuming from your response all of this is in one file, the test method doesn't actually need to be in a separate class, I tend to just define mine in the class like so: public static testmethod void TestClassName() { // etc. } - Matt Lacey
They're actually in two seperate files, and at the moment it's being done directly to production. I might just try it in a sandbox and see how it goes. - Apexer

1 Answers

4
votes

A nice shorthand:

public List<TestObject__c> objects {get; private set;}

It creates the getter/setter for you and looks cleaner imo. As for your current issue, yes - it's hard saving code directly into production - especially with test classes in separate files.

Best to do this in a sandbox/dev org then deploy to production (deploy to server - Force.com IDE). But if you must save directly into production then I'd combine test methods with your class. But in the long run, having @test atop a dedicated test class is the way to go. It won't consume your valuable resources this way.