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
Waqas AliWaqas Ali 

How to refer PageReference method from test class

I am new to apex, I have created a button to call the apex class through the visual force page. 

Here is my visual force page code. 
<apex:page standardController="Opportunity"
 extensions="myclass"
 action="{!autoRun}">
</apex:page>
Here is my apex class.
public class myclass {
    private final Opportunity o;
    String tmp;
   public myclass(ApexPages.StandardController stdController) {
        this.o = (Opportunity)stdController.getRecord();
    }
    public PageReference autoRun() {
        String theId = ApexPages.currentPage().getParameters().get('id');
 
        for (Opportunity o:[select id, name, AccountId,  from Opportunity where id =:theId]) {
 
                 //Create the Order
                    Order odr = new Order( 
                    OpportunityId=o.id
                    ,AccountId = o.AccountId
                    ,Name = o.Name
                    ,EffectiveDate=Date.today()
                    ,Status='Draft'
                    );
                insert odr;
                tmp=odr.id;            
              }                 
        PageReference pageRef = new PageReference('/' + tmp); 
        pageRef.setRedirect(true);
        return pageRef;
      }
}
I want to create test class. I don't know how to refer PageReference autoRun() method from test class. Guys need help if some one can tell me about test class of this apex class. 
 
Best Answer chosen by Waqas Ali
Vivek DeshmaneVivek Deshmane
Hi,
Please try this and mark the best answer.
@isTest
private class testMyController
{
private static testMethod void testAutoRun() {

 test.startTest();
   PageReference pageRef = Page.yourPageName;
  Account acc = new Account(Name='Abce');
  insert acc;
  Opportunity  testOppty = new Opportunity();
  testOppty.name='testOppty';
  testOppty.AccountId=acc.id;
   testOppty.StageName='Open';
  testOppty.CloseDate=System.today();
  insert testOppty;
   Test.setCurrentPage(pageRef);
   pageRef.getParameters().put('id',testOppty.id);
   ApexPages.StandardController sc = new ApexPages.standardController(testOppty);
   Myclass  controller = new Myclass(sc);
   System.assertNotEquals(null,controller.autoRun());
   
   test.stopTest();
}

}

Best Regards,
-Vivek

All Answers

Vivek DeshmaneVivek Deshmane
Hi ,
Please try below code and let me know if it will help you.
@isTest
private class testMyController
{
private static testMethod void testAutoRun() {

 test.startTest();
   PageReference pageRef = Page.yourPageName;
  Account acc = new Account(Name='Abce');
  insert acc;
  Opportunity  testOppty = new Opportunity();
  testOppty.name='testOppty';
  testOppty.AccountId=acc.id;
  insert testOppty;
   Test.setCurrentPage(pageRef);
   pageRef.ApexPages.currentPage().getParameters().put('id',testOppty.id);
   ApexPages.StandardController sc = new ApexPages.standardController(testOppty);
   Myclass  controller = new Myclass(sc);
   System.assertNotEquals(null,controller.autoRun());
   System.assertEquals(controller.o, testOppty);
   test.stopTest();
}

}

Best Regards,
-Vivek
Waqas AliWaqas Ali

Hi Vivek 

i tried your code. Here is the error.
Error: Compile Error: Expression of type System.PageReference has no member named apexpages at line 19 column 4
How to fix this ?

Sorry if i ask some stupid thing. 

Thanks

Waqas Ali

Waqas AliWaqas Ali

Sorry i did not mention in my last coment that Error is on this line 

pageRef.ApexPages.currentPage().getParameters().put('id',testOppty.id);
Vivek DeshmaneVivek Deshmane
Hi,
Please try this and mark the best answer.
@isTest
private class testMyController
{
private static testMethod void testAutoRun() {

 test.startTest();
   PageReference pageRef = Page.yourPageName;
  Account acc = new Account(Name='Abce');
  insert acc;
  Opportunity  testOppty = new Opportunity();
  testOppty.name='testOppty';
  testOppty.AccountId=acc.id;
   testOppty.StageName='Open';
  testOppty.CloseDate=System.today();
  insert testOppty;
   Test.setCurrentPage(pageRef);
   pageRef.getParameters().put('id',testOppty.id);
   ApexPages.StandardController sc = new ApexPages.standardController(testOppty);
   Myclass  controller = new Myclass(sc);
   System.assertNotEquals(null,controller.autoRun());
   
   test.stopTest();
}

}

Best Regards,
-Vivek
This was selected as the best answer
Amit Chaudhary 8Amit Chaudhary 8
Hi Waqas Ali,

I found below issue in your mail class.
DML inside the for loop.
Please modify your class like below class:-
public class myclass 
{
    private final Opportunity o;
    String tmp;
    public myclass(ApexPages.StandardController stdController) 
	{
        this.o = (Opportunity)stdController.getRecord();
    }
    public PageReference autoRun() 
	{
		String theId = ApexPages.currentPage().getParameters().get('id');
			
		List<Order> lstOrder = new List<Order>();
        for (Opportunity o:[select id, name, AccountId,  from Opportunity where id =:theId] ) 
		{
		
                    Order odr = new Order( 
                    OpportunityId=o.id
                    ,AccountId = o.AccountId
                    ,Name = o.Name
                    ,EffectiveDate=Date.today()
                    ,Status='Draft'
                    );
					
					lstOrder.add(odr);
        }
		if(lstOrder.size() > 0 )
		{	
			insert lstOrder;
			return new PageReference('/'+lstOrder[0].id);
		}
		else
		{
			ApexPages.addmessage(new ApexPages.message(ApexPages.severity.WARNING,'No ORder created'));
		}	
    }
}

If you want the you can remove the String theId = ApexPages.currentPage().getParameters().get('id'); line also.
public PageReference autoRun() 
	{
			
		List<Order> lstOrder = new List<Order>();
        for (Opportunity o:[select id, name, AccountId,  from Opportunity where id =:o.id] ) 
		{
		
                    Order odr = new Order( 
                    OpportunityId=o.id
                    ,AccountId = o.AccountId
                    ,Name = o.Name
                    ,EffectiveDate=Date.today()
                    ,Status='Draft'
                    );
					
					lstOrder.add(odr);
        }
		if(lstOrder.size() > 0 )
		{	
			insert lstOrder;
			return new PageReference('/'+lstOrder[0].id);
		}
		else
		{
			ApexPages.addmessage(new ApexPages.message(ApexPages.severity.WARNING,'No ORder created'));
		}	
    }




Modify your page like below. If any error will come
<apex:page standardController="Opportunity"
 extensions="myclass"
 action="{!autoRun}">
<apex:pageMessages ></apex:pageMessages>

</apex:page>

Then you can try below test class:-
 
@isTest
private class testMyController
{
	private static testMethod void testAutoRun() 
	{
		Account acc = new Account(Name='Abce');
		insert acc;
		
		Opportunity  testOppty = new Opportunity();
		testOppty.name='testOppty';
		testOppty.AccountId=acc.id;
		testOppty.StageName='Open';
		testOppty.CloseDate=System.today();
		insert testOppty;

		test.startTest();
		
			
			PageReference pageRef = Page.yourPageName;
			Test.setCurrentPage(pageRef);
			
			pageRef.getParameters().put('id',testOppty.id);
			ApexPages.StandardController sc = new ApexPages.standardController(testOppty);
			
			Myclass  controller = new Myclass(sc);
			controller.autoRun();

		test.stopTest();
	}

}

Please see below blog how to create test classes in salesforce
http://amitsalesforce.blogspot.in/2015/06/best-practice-for-test-classes-sample.html

Please let us know if this will help you.

Thanks,
Amit Chaudhary
Waqas AliWaqas Ali
Thank you guys. 
Praveen Venkata BPraveen Venkata B
I have found one more issue in your code. When you use list.size()>0, this consumes some system time, instead use list.isEmpty().
This improved code performance.

Happy coding !!