5

I'm trying to write an apex test for submitting a Visualforce apex:form. The page is very basic:

<apex:page controller="MyController">
  <apex:form>
    <apex:inputField value="{!settings.val1__c}"/>
    <apex:commandButton action="{!save}" value="Save"/>
  </apex:form>
</apex:page>

The controller is also basic:

public with sharing class MyController {
  public MySettings__c settings {get; set;}

  public MyController() {
    settings = MySettings__c.getOrgDefaults();
    if (settings == null || settings.id == null) {
      upsert new MySettings__c(SetupOwnerId = UserInfo.getOrganizationId());
      settings = MySettings__c.getOrgDefaults();
  }

  public PageReference save() {
    update settings;
    return null;
  }
}

In the test class, I have gotten only this far:

PageReference page = new PageReference('/apex/MyPage');
Test.setCurrentPage(page);

And now I am at a loss as to how to fill in values for my VF page so that I can try saving it and make sure that the value was saved. Any idea how I can fill in VF form values from an apex test?

Thanks!

5

The Visualforce components just access the controller's properties and methods, so in your test class you call those directly.

Example:

// Arrange the components
MySettings__c originalValue = MySettings__c.getOrgDefaults();
PageReference pageRef = Page.YourPageNameHere;
Test.setCurrentPage(pageRef);      
MyController controller = new MyController();

// Act
controller.settings.val1__c = 'New value';
controller.save();
MySettings__c updatedValue = [SOQL to retrieve new object];

// Assert
System.assertEquals(updatedValue, originalValue, 'Error message');

See the developer docs for more information.

| improve this answer | |
4

You just need to create an instance of your controller, set the field, then check it was set correctly. Something like this:

String testVal = 'TESTVAL';
MyController() c = new MyController();
c.settings.val1__c = testVal;
c.save();
System.assertEquals(testVal, MySettings__c.getOrgDefaults().val1__c, 
    'Saved setting is not correct!');
| improve this answer | |

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.