I need to create a test class for an apex controller which overrides the normal save function in my visualforce page and redirect the user to a custom page.

Can someone help me do this? I'm not sure what to test the controller on.


public class force_NewOrderLogic {

          ApexPages.StandardController stdController;
          public force_NewOrderLogic(ApexPages.StandardController con){
              stdController = con;

public PageReference saveAndRedirect() {
  if(stdController.save() != null) {
    PageReference redirectPage = Page.force_OrderDetail;
    return redirectPage;
  } return null;


Test Class

private class test_NewOrderLogic {

    static testMethod void myTest() {

        PageReference pageRef = Page.force_OrderDetail;

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

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

        // Verify that the success page displays
        System.assertEquals('/apex/force_OrderDetail', nextPage);


I have attempted a very basic draft using some of the links provided in the answers, however I get the following error with the code above:

Error: Compile Error: Constructor not defined: [force_NewOrderLogic].() at line 9 column 42


See example here. The controller in the example also overrides the save function just like your requirement.


Because you set the constructor of the controller to accept a standard controller whenever you create a new instance of the force_NewOrderLogic controller you need to provide a standard controller in your test method.

These are the lines in your custom controller :

public force_NewOrderLogic(ApexPages.StandardController con){
              stdController = con;

So in your test method before creating a new instance of your custom controller you need to create an instance of the standard controller of the object you want to save:

ApexPages.StandardController sc = new ApexPages.standardController(your sobject here);

and pass it to your custom controller

force_NewOrderLogic controller = force_NewOrderLogic(sc);

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.