function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
cnewmancnewman 

Apex Test Class Help

Hi All,

I'm really struggling to get my head around apex test clases. I've build a very basic save controller to help with a function on a small but of VisualForce page. It simply redirects back to the apex page when you save the record.
I just don't know how to build the test class for it. Here's my code:

public with sharing class DemoExtension
{
   ApexPages.StandardController stdCtrl;
   // extension constructor
   public DemoExtension(ApexPages.StandardController std)
   {
      stdCtrl=std;
   }

   public PageReference save()
   {
      stdCtrl.save();
      PageReference pr=Page.Demo_Q_and_A;
      pr.setRedirect(false);
      return pr;
   }
}
How do I build a class to test the save function?

Thanks
Best Answer chosen by cnewman
Pavan Kumar KajaPavan Kumar Kaja
Try below code.

@istest()
private class TestDemoExtension{

    static testMethod void myUnitTestDemoExtension() {

  // insert the standard controller record like below
  Account acc = new Account();
  acc.Name = 'Test'
  insert acc;
 
  ApexPAges.StandardController sc = new ApexPages.StandardController(acc);
        DemoExtension testExt = new DemoExtension(sc);
        testExt.save();
}
}

All Answers

Pavan Kumar KajaPavan Kumar Kaja
Try below code.

@istest()
private class TestDemoExtension{

    static testMethod void myUnitTestDemoExtension() {

  // insert the standard controller record like below
  Account acc = new Account();
  acc.Name = 'Test'
  insert acc;
 
  ApexPAges.StandardController sc = new ApexPages.StandardController(acc);
        DemoExtension testExt = new DemoExtension(sc);
        testExt.save();
}
}
This was selected as the best answer
cnewmancnewman
Thanks Ashi, I'm still stuck though, it still won't deploy to my production. The test passes in Sandbox. I'm then trying to deploy them both (My class and the test class) to production but it says only 73% passes??

Do I deply test clases differently to live ones?

Chris
Pavan Kumar KajaPavan Kumar Kaja
Post the screen which lines were not covered(red). will write code to test the remaining lines. ideally it should greater than 75 % to move to prod and the best practice is 95 %.
cnewmancnewman
I found an installed app that had some untested lines, that was dragging it down, back up to 93% now!

Thank you so much for your help!