+ Start a Discussion
sgottreusgottreu 

How to test a PageReference Method in an Apex Class

I have a class with two methods.  The main method pulls data from the db and creates a list of Opportunities.  The PageReference method creates a document using a Page that pulls it's data from the main method.  It thens saves this PDF in the Documents folder and as an Attachment on the Opportunity. 

 

I have written test methods for both pieces of code but I'm stuck at 55% coverage.  I'm trying to figure out what I'm missing.  Thank you in advance.


 

    public class ProbeQuote {
        Schema.DescribeFieldResult F = Product2.Family.getDescribe();
        List<Schema.PicklistEntry> P = F.getPicklistValues();

        public Opportunity Probe { get; set; }

        public String pdfName;

        public ID id = ApexPages.CurrentPage().getParameters().get('id');

        public List<Opportunity> ProbeProducts = new List<Opportunity>();

        Integer Counter = 1;

        public ApexPages.StandardController controller;

        public ProbeQuote(ApexPages.StandardController stdController) {
            controller = stdController;
            //quoteid = stdController.getRecord().id;
            //ID id = '0068000000NyTHe';

            for (Schema.PicklistEntry fam:P){
            Integer i = 0;
            String FamilyLabel = fam.GetLabel();

            Probe = [SELECT o.Id, o.Name, o.Amount, o.ProductFamily__c, (SELECT op.Quantity, op.UnitPrice,
op.TotalPrice,op.PricebookEntry.Name, op.OpportunityId, op.PricebookEntry.ProductCode,
            op.PricebookEntry.Product2.Family, op.LineCount__c 
            FROM OpportunityLineItems op WHERE op.PricebookEntry.Product2.Family = :FamilyLabel)
            FROM Opportunity o where Id = :id];

            Probe.Amount = 0;
            Probe.ProductFamily__c = FamilyLabel;

            for(i=0;i<Probe.opportunityLineItems.size();i++) {
                Probe.Amount += Probe.opportunityLineItems[i].TotalPrice;  
                Probe.opportunityLineItems[i].LineCount__c = Counter;
                Counter++;
            }

            ProbeProducts.add(Probe);
            }
        }

        public List<Opportunity> getProbeProducts() {
            return ProbeProducts;
        }

        public PageReference attachQuote() {
            Opportunity Opp = [SELECT o.Id, o.Name, o.Amount, o.ProductFamily__c 
            FROM Opportunity o where Id = :id]; 

            pdfName = Opp.Name + '.pdf';

            /* Get the page definition */
            PageReference pdfPage = new PageReference( '/apex/ProbeQuote' );

            /* set the quote id on the page definition */
            pdfPage.getParameters().put('id',id);

            /* generate the pdf blob */
            Blob pdfBlob = pdfPage.getContent();

            /* create the attachment against the quote */
            Attachment a = new Attachment(parentId = id, name=pdfName, body = pdfBlob);

            /* insert the attachment */
            insert a;

            /* Now create document to show up in Documents Tab in Quotes Folder */

            Folder f = [SELECT Id, Name FROM Folder WHERE Name = 'Quotes'
            AND Type = 'Document'];

            Document d = new Document();

            d.Name = pdfName;

            //d.DeveloperName = pdfName;

            d.ContentType = 'application/pdf';

            d.Body = pdfBlob;

            d.FolderId = f.Id;

            insert d;


            /* send the user back to the quote detail page */
            return controller.view();
        }

        public static testMethod void testProbeQuote() {
            Id id;
            Opportunity testProbe;
            List<Opportunity> testProbeProducts = new List<Opportunity>();
            Integer Counter = 1;

            Schema.DescribeFieldResult F = Product2.Family.getDescribe();
            List<Schema.PicklistEntry> P = F.getPicklistValues();

            Opportunity testOppty = new opportunity (Name = 'Force Monkey 4x4',
            StageName = 'Prospect', Amount = 2000, CloseDate = System.today() );

            insert testOppty;

            id = testOppty.id;

            // Insert test Truck OpportunityLineItem

            OpportunityLineItem testOLI = new OpportunityLineItem (Quantity = 5,
            UnitPrice = 100, OpportunityId = testOppty.id, PricebookEntryId = '01u80000002XFfKAAW');

            insert testOLI;

            for (Schema.PicklistEntry fam:P){
                Integer i = 0;
                String FamilyLabel = fam.GetLabel();

                testProbe = [SELECT o.Id, o.Name, o.Amount, o.ProductFamily__c, (SELECT op.Quantity, op.UnitPrice, op.TotalPrice,op.PricebookEntry.Name, op.OpportunityId, op.PricebookEntry.ProductCode, op.PricebookEntry.Product2.Family, op.LineCount__c 
            FROM OpportunityLineItems op WHERE op.PricebookEntry.Product2.Family = :FamilyLabel)
            FROM Opportunity o where Id = :id];
                testProbe.Amount = 0;
                testProbe.ProductFamily__c = FamilyLabel;

                for(i=0;i<testProbe.opportunityLineItems.size();i++) {
                    testProbe.Amount += testProbe.opportunityLineItems[i].TotalPrice;  
                    testProbe.opportunityLineItems[i].LineCount__c = Counter;
                    Counter++;
                }

                testProbeProducts.add(testProbe);
            }


            PageReference pg = Page.yourVFpageName; Test.setCurrentPage(pg); ApexPages.currentPage().getParameters().put('id', testOppty.id);

            // Instantiate custom ProbeQuote controller

            //testProbeProducts.add(testOppty);

            System.assertEquals (testProbeProducts[0].Name, 'Force Monkey 4x4');

            ApexPages.StandardController stc = new ApexPages.StandardController(testOppty);
            ProbeQuote qe = new ProbeQuote(stc);
        }

        public static testMethod void  testattachQuote() {
            String pdfName;

            Opportunity testOppty = new opportunity (Name = 'Force Monkey 4x4',
            StageName = 'Prospect', Amount = 2000, CloseDate = System.today() );

            insert testOppty;

            ID id = testOppty.id;

            // Insert test Truck OpportunityLineItem

            OpportunityLineItem testOLI = new OpportunityLineItem (Quantity = 5,
            UnitPrice = 100, OpportunityId = testOppty.id, PricebookEntryId = '01u80000002XFfKAAW');

            insert testOLI;

            pdfName = testOppty.Name + '.pdf';

            /* Get the page definition */
            PageReference pdfPage = new PageReference( '/apex/ProbeQuote' );

            /* set the quote id on the page definition */
            pdfPage.getParameters().put('id',id);

            /* generate the pdf blob */
            Blob pdfBlob = pdfPage.getContent();

            /* create the attachment against the quote */
            Attachment a = new Attachment(parentId = id, name=pdfName, body = pdfBlob);

            /* insert the attachment */
            insert a;

            /* Now create document to show up in Documents Tab in Quotes Folder */

            Folder f = new Folder (Name = 'Quotes', Id = '00l80000001DJ2aAAG', Type = 'Document');

            System.assertEquals (f.Name, 'Quotes');

            Document d = new Document(Name = pdfName, ContentType = 'application/pdf',
            Body = pdfBlob, FolderId = f.Id);

            insert d;

            PageReference pg = Page.yourVFpageName; Test.setCurrentPage(pg); ApexPages.currentPage().getParameters().put('id', testOppty.id);

            // Instantiate custom ProbeQuote controller

            ApexPages.StandardController stc = new ApexPages.StandardController(testOppty);
            ProbeQuote qe = new ProbeQuote(stc);

        }

    }

 

Walter@AdicioWalter@Adicio

 

You want to look into the standard method called "Test.setCurrentPage()".

 

public static PageReference redirectToAppropriateAlertsPage_live() { if( alwaysShowTheseInAlertsPageList_live.size()==0) { PageReference acctPage = new PageReference('https://na3.salesforce.com/home/home.jsp'); acctPage.setRedirect(true); return acctPage; } else {PageReference acctPage = new PageReference('https://na3.salesforce.com/apex/alert'); acctPage.setRedirect(true); return acctPage; } return null;}

 

 

Test.setCurrentPage( redirectToAppropriateAlertsPage_live() );

 

 

 

System.debug('the current page is...' +ApexPages.currentPage() ); System.assertEquals('/apex/alert', ApexPages.currentPage() );

 

sgottreusgottreu

I've made some updates to the code. I know I have some redunancy but I was just trying everything to make it work. I'm now up to 60% coverage.  I don't have any other get/set functions to check that I know of.

 

Here's the updated test methods.  The actual functions and methods can be seen above.  I'm hitting the message limit on this post.

 

 

public class ProbeQuote {
    Schema.DescribeFieldResult F = Product2.Family.getDescribe();
    List<Schema.PicklistEntry> P = F.getPicklistValues();
   
    public Opportunity Probe { get; set; }
   
    private String pdfName;
   
    public ID id = ApexPages.CurrentPage().getParameters().get('id');
   
    public List<Opportunity> ProbeProducts = new List<Opportunity>();
   
    Integer Counter = 1;
   
    public ApexPages.StandardController controller;

   
public static testMethod void testProbeQuote() {
        Id id;
        Opportunity testProbe;
        Integer Counter = 1;
       
        Schema.DescribeFieldResult F = Product2.Family.getDescribe();
        List<Schema.PicklistEntry> P = F.getPicklistValues();
       
        Opportunity testOppty = new opportunity (Name = 'Force Monkey 4x4',
           StageName = 'Prospect', Amount = 2000, CloseDate = System.today() );
       
        insert testOppty;
       
        PageReference pg = Page.yourVFpageName; Test.setCurrentPage(pg); ApexPages.currentPage().getParameters().put('id', testOppty.id);

        id = ApexPages.CurrentPage().getParameters().get('id');
       
        Opportunity Opp = [SELECT o.Id, o.Name, o.Amount, o.ProductFamily__c 
                  FROM Opportunity o where Id = :testOppty.Id];
                 
        System.assertEquals(Opp.Id, testOppty.Id);
       
        for (Schema.PicklistEntry fam:P){
            Integer i = 0;
            String FamilyLabel = fam.GetLabel();
           
                        // Insert test Truck OpportunityLineItem
       
            Product2 testProd = new Product2 (Name = 'SalesForce Test Method',
                    IsActive = True, Family = FamilyLabel);
           
            insert testProd;
           
            Pricebook2 testPB = [select ID from Pricebook2 where IsStandard = TRUE];
           
            PriceBookEntry testPBE = new PricebookEntry (IsActive = True, UnitPrice = 100,
                        Product2Id = testProd.Id, Pricebook2Id = testPB.Id,
                        UseStandardPrice = False);
           
            insert testPBE;
           
            OpportunityLineItem testOLI = new OpportunityLineItem (Quantity = 5,
               UnitPrice = 100, OpportunityId = testOppty.id,
               PricebookEntryId = testPBE.Id);
           
            insert testOLI;
       
            testProbe = [SELECT o.Id, o.Name, o.Amount, o.ProductFamily__c, (SELECT op.Quantity, op.UnitPrice, op.TotalPrice,
                      op.PricebookEntry.Name, op.OpportunityId, op.PricebookEntry.ProductCode,
                      op.PricebookEntry.Product2.Family, op.LineCount__c 
                      FROM OpportunityLineItems op WHERE op.PricebookEntry.Product2.Family = :FamilyLabel)
                      FROM Opportunity o where Id = :Opp.Id];
                     
            System.assertEquals(Opp.Id, testProbe.Id);
               
            testProbe.Amount = 0;
            testProbe.ProductFamily__c = FamilyLabel;
                 
            for(i=0;i<testProbe.opportunityLineItems.size();i++) {
                testProbe.Amount += testProbe.opportunityLineItems[i].TotalPrice;
                testProbe.opportunityLineItems[i].LineCount__c = Counter;
                Counter++;
            }
            update testProbe;
           
            System.assertEquals (testProbe.Amount, 500);
        }
          
          ApexPages.StandardController stc = new ApexPages.StandardController(testOppty);
          ProbeQuote qe = new ProbeQuote(stc);
         
            List<Opportunity> testProbeProducts = qe.Getprobeproducts();
            System.assertEquals (testProbeProducts[0].Name, 'Force Monkey 4x4');
       
    }
   
    public static testMethod void testattachQuote() {
        String pdfName;
       
        Opportunity testOppty = new opportunity (Name = 'Force Monkey 4x4',
           StageName = 'Prospect', Amount = 2000, CloseDate = System.today() );
       
        insert testOppty;
       
        OpportunityLineItem testOLI = new OpportunityLineItem (Quantity = 5,
           UnitPrice = 100, OpportunityId = testOppty.id, PricebookEntryId = '01u80000002XFfKAAW');
       
        insert testOLI;
       
        Opportunity Opp = [SELECT o.Id, o.Name, o.Amount, o.ProductFamily__c 
                  FROM Opportunity o where Id = :testOppty.Id];
                 
        System.assertEquals(Opp.Id, testOppty.Id);
 
                     
        pdfName = testOppty.Name + '.pdf';
                     
        /* Get the page definition */
        PageReference pdfPage = new PageReference( '/apex/ProbeQuote' );
        Test.setCurrentPage(pdfPage);
       
        /* set the quote id on the page definition */
        pdfPage.getParameters().put('id',Opp.Id);
       
        System.assertEquals(pdfPage.getParameters().get('id'), Opp.Id);
       
        /* generate the pdf blob */
        Blob pdfBlob = pdfPage.getContent();
       
        /* create the attachment against the quote */
        Attachment a = new Attachment(parentId = Opp.Id, name=pdfName, body = pdfBlob);
      
        /* insert the attachment */
        insert a;
       
        Attachment att = [SELECT Id, Name
                      FROM Attachment where Id = :a.Id];
                     
        System.assertEquals(att.Id, a.Id);

        /* Now create document to show up in Documents Tab in Quotes Folder */
       
        Folder f = new Folder (Name = 'Quotes', Type = 'Document', Id = '00l80000001DJ2aAAG');
       
        //insert f;
       
        Folder fo = [SELECT Id, Name
                      FROM Folder where Id = :f.Id];
       
        System.assertEquals (fo.Id, f.Id);
     
        Document d = new Document(Name = pdfName, ContentType = 'application/pdf',
                Body = pdfBlob, FolderId = f.Id);
       
        insert d;
       
        Document doc = [SELECT Id, Name
                      FROM Document where Id = :d.Id];
       
        System.assertEquals (d.Id, doc.Id);
       
        PageReference pg = Page.yourVFpageName; Test.setCurrentPage(pg); ApexPages.currentPage().getParameters().put('id', Opp.Id);
       
        // Instantiate custom ProbeQuote controller
       
        ApexPages.StandardController stc = new ApexPages.StandardController(testOppty);
        ProbeQuote qe = new ProbeQuote(stc);
       
        List<Opportunity> testProbeProducts = qe.Getprobeproducts();
        System.assertEquals (testProbeProducts[0].Name, 'Force Monkey 4x4');
       
        String nextPage = stc.save().getUrl();
       
        String testId = Opp.Id;
       
        testId = testId.substring(0,15);
       
        //Check that the save() method returns the proper URL.
        System.assertEquals('/'+testId, nextPage);
    }
   
   
}

 

mh1974mh1974
Have you used the code review screen to see which lines have and have not been tested?  Once your test has run,  you can click on the %-code covered to view the code, see which pieces have been hit and update your tests accordingly.
sgottreusgottreu

I have been unable to install the Force.Com IDE in both Windows and Linux so i have been using the UI Interface in Salesforce.  I was able to get a screen grab of what code is not being covered.  It's the PageReference AttachQuote function.  Everything in my main function is covered. 

 

Thanks for pointing out the feature of seeing which lines of code were covered.  Didn't know that was in there.

 

Any help on tracking this down is appreciated.

 

Walter@AdicioWalter@Adicio

I didnt know about %-code , thank you.

 

I'm running foce.com in eclipse 3.2 - 2.5 on opensuse 11.1 KDE, ubuntu and kubuntu 9.04, but only by just down the archive from eclipse, extract it and just run it from that folder. For all these disto's if i use the package in the repo i get errors. I'm only using 3.4 now for force.com ide, cause i read its the current recommended, and 3.2 is no longer supported.

sgottreusgottreu

So I had an epiphany this morning. I had downloaded an app from AppExchange that had the same functionality in it that I was using.  I looked at their test method and I figured out the problem.

 

To test a PageReference method in your code simply call it like the function that it is.  I added one line and I now have 100% coverage.

 

    public static testMethod void testProbeQuote() {


          /*****

          Other code that creates Opportunity and Line Items to test
          ******/         
          
          ApexPages.StandardController stc = new ApexPages.StandardController(testOppty);
          ProbeQuote qe = new ProbeQuote(stc);
         
          List<Opportunity> testProbeProducts = qe.Getprobeproducts();
          System.assertEquals (testProbeProducts[0].Name, 'Force Monkey 4x4');
           

          /*****  This is all you need to test a PageReference method/function *****/

          qe.attachQuote();
       
    }

Message Edited by sgottreu on 07-11-2009 05:03 AM
KPGUPTAKPGUPTA

I also have the same prob.. Can anybody help me for this...

 

public PageReference init() {
        
        String oldId = ApexPages.currentPage().getParameters().get('oid');
        
        if (oldId == null) return null;
        
        List<KnowledgeArticleVersion> articles = new List<KnowledgeArticleVersion>();
        articles = [SELECT Id FROM KnowledgeArticleVersion WHERE (UrlName = :oldId) AND (PublishStatus = 'Online')]; 
        
        if (!articles.IsEmpty()) {
            String newId = articles[0].Id;
            System.debug('test-->'+newId );
            PageReference newReference = new PageReference('https://.my.salesforce.com/knowledge/publishing/articleOnlineDetail.apexp');
            newReference.getParameters().put('id', newId);
            newReference.setRedirect(true);
            
            return newReference;
        }
        
        return null;
    }
test code is-------->
 private static testMethod void testInit() {
        
        PageReference testPage = Page.oMarketoArticle;
        testPage.getParameters().put('oid', '12345');
        
        Test.setCurrentPage(testPage);
       
        Test.StartTest();
        
        oMarketoArticleController controller = new oMarketoArticleController();
        
        controller.init();
         List<KnowledgeArticleVersion> articles = new List<KnowledgeArticleVersion>();
        articles = [SELECT Id FROM KnowledgeArticleVersion WHERE (UrlName = :'testPage') AND (PublishStatus = 'Online')]; 
        //newid = 
         PageReference testPage1 = Page.oMarketoArticle;
        testPage1.getParameters().put('id', '12345');
       
        Test.setCurrentPage(testPage1);
        
        
        Test.StopTest();
    }
i got 58 5 of code covergage. pls reply if somebody knw how to increase more...
thanks
SteveBowerSteveBower

Do you actually *have* any records in KnowlegeArticleVersion with a UrlName of "12345" with PublishStatus of 'Online'?  If not, then you must create some and insert them as part of the test setup so that the query in the init() will discover some records.

 



private static testMethod void testInit() {

    // create an article here so that init() will find it.
    KnowledgeArticleVersion myArticle = new KnowledgeArticleVersion(UrlName='12345', PublishStatus='Online',.....);
    insert myArticle;
        
    PageReference testPage = Page.oMarketoArticle;
    testPage.getParameters().put('oid', '12345');
        
    Test.setCurrentPage(testPage);
    Test.StartTest();
        
    oMarketoArticleController controller = new oMarketoArticleController();
        
    // call the init and check the results of the pageReference.
    pageReference p = controller.init();
    system.assertEquals('https://.my.salesforce.com/knowledge/publishing/articleOnlineDetail.apexp', p.getUrl()); 
    system.assertEquals(myArticle.id, p.getParameters().get(id));

    Test.StopTest();

// You should also test the cases where 'oid' is null, and where oid is not null, but there are no articles returned from the query. In those cases you're returning a null pageReference shich you can check with system.assertEquals(null,p); 

// You should try it with another article which has the correct UrlName but is Offline to generate the null case.

 

Lastly, consider that if you're not checking any of the results of your trigger with system.assert calls, you're not really testing anything.  Merely getting code coverage doesn't mean that you've tested anything... just that you've called it.

 

Best, Steve.