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
GrrrrrrrrrrrrrGrrrrrrrrrrrrr 

54% coverage on test method ... almost there ... need a little help

Jeff Douglas wrote a wonderful chunk of code ( http://blog.jeffdouglas.com/2010/07/13/building-a-dynamic-search-page-in-visualforce/ )

And I am working on applying it to my org.  I have it in my sandbox and it works awesome!  But I am having trouble getting anything over 50% code coverage.

 

Can someone help me to figure out the last little bit?  Thanks in advance!

 

Here is my test so far:

 

@isTest(SeeAllData=true)
private with sharing class TestOpportunitySearchController 
{               
    static testMethod void myTest()
    {
        Test.startTest();
        date testdate = System.today().addDays(+1);
        Account testaccount = new Account(Name = 'test', Trident_Contract_Manager__c = 'test');
        insert testaccount;
                   
        Opportunity testrenewal =  new Opportunity(accountId = testaccount.Id, Amount = 100.00, Closedate = testdate, Description = 'test', Name = 'test', Stagename = 'Baseline', Probability = 100, OwnerId = UserInfo.getUserId(), 
                                                   Coverage_Start_Date__c = System.today().addDays(-15), Coverage_End_Date__c = System.today().addDays(100));
        insert testrenewal;                 

        ApexPages.StandardController sc1 = new ApexPages.StandardController(testrenewal);
        OpportunitySearchController controller1 = new OpportunitySearchController(sc1);           
        controller1.runQuery();
        controller1.runSearch();
        controller1.toggleSort();


        Test.stopTest();
    }
}

 Here is my missing coverage (red indicates not covered):  I cant figure out how to call the 'stages' and 'managers' methods.

 

 line	 source
 1	  public with sharing class OpportunitySearchController {
 2	   public OpportunitySearchController(ApexPages.StandardController controller) { soql = 'select name, account.name, Trident_Contract_Manager2__c, stagename from opportunity where name != null'; runQuery(); }
 3	   private String soql {get;set;}
 4	   public List<Opportunity> renewals {get;set;}
 5	   public String sortDir { get { if (sortDir == null) { sortDir = 'asc'; } return sortDir; } set; }
 6	   public String sortField { get { if (sortField == null) {sortField = 'name'; } return sortField; } set; }
 7	   public String debugSoql { get { return soql + ' order by ' + sortField + ' ' + sortDir + ' limit 40'; } set; }
 8	  
 9	   public void toggleSort() { sortDir = sortDir.equals('asc') ? 'desc' : 'asc'; runQuery(); }
 10	   public void runQuery() {
 11	   try { renewals = Database.query(soql + ' order by ' + sortField + ' ' + sortDir + ' limit 40'); } catch (Exception e) { ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR, 'Ooops!')); } }
 12	   public PageReference runSearch() {
 13	   String name = Apexpages.currentPage().getParameters().get('name');
 14	   String account = Apexpages.currentPage().getParameters().get('account');
 15	   String manager = Apexpages.currentPage().getParameters().get('manager');
 16	   String stage = Apexpages.currentPage().getParameters().get('stage');
 17	   soql = 'select name, account.name, Trident_Contract_Manager2__c, stagename from opportunity where name != null';
 18	   if (!name.equals('')) soql += ' and name LIKE \''+String.escapeSingleQuotes(Name)+'%\'';
 19	   if (!account.equals('')) soql += ' and account.name LIKE \''+String.escapeSingleQuotes(account)+'%\'';
 20	   if (!manager.equals('')) soql += ' and Trident_Contract_Manager2__c LIKE \''+manager+'\'';
 21	   if (!stage.equals('')) soql += ' and stagename LIKE \''+stage+'\'';
 22	   runQuery();
 23	   return null;
 24	   }
 25	  
 26	  
 27	   public List<String> stages {
 28	   get { if (stages == null) { stages = new List<String>();
 29	   Schema.DescribeFieldResult field = Opportunity.stagename.getDescribe();
 30	   for (Schema.PicklistEntry f : field.getPicklistValues()) stages.add(f.getLabel()); }
 31	   return stages;
 32	   }
 33	   set;
 34	   }
 35	   public List<String> managers {
 36	   get { if (managers == null) { managers = new List<String>();
 37	   Schema.DescribeFieldResult field = Account.Trident_Contract_Manager__c.getDescribe();
 38	   for (Schema.PicklistEntry f : field.getPicklistValues()) managers .add(f.getLabel());
 39	   }
 40	   return managers;
 41	   }
 42	   set;
 43	   }
 44	  }

 

 

 

 Thank you!

Best Answer chosen by Admin (Salesforce Developers) 
logontokartiklogontokartik

Hmm. looks like your code is looking for Current Page parameters and you didnt set them in your test class. Include these lines in your test class before you instantiate your controller class. (immediately after insert testrenewal)

 Pagereference testPage = Page.<your Visualforce page name>;
 Test.setCurrentPagereference(testPage);
 Apexpages.currentPage().getParameters().put('name','test');
 Apexpages.currentPage().getParameters().put('account','test');
 Apexpages.currentPage().getParameters().put('manager','test');         
Apexpages.currentPage().getParameters().put('stage','Baseline');

PS : It would be best practice to generally handle exceptions in your class (maybe using a try catch block)

All Answers

logontokartiklogontokartik

Just try adding 

 

List<String> stgs = controller1.stages;
List<String> mgs = controller1.managers;

 

That should call your getters for the stages and managers. 

GrrrrrrrrrrrrrGrrrrrrrrrrrrr

Hi Kartik.

Thanks for the post.

I added the two lines to my test method, but it didnt change my coverage.

Its telling me "attempt to de-reference a null object"  

but what is null?

@isTest(SeeAllData=true)
private with sharing class TestOpportunitySearchController 
{               
    static testMethod void myTest()
    {
        Test.startTest();
        date testdate = System.today().addDays(+1);
        Account testaccount = new Account(Name = 'test', Trident_Contract_Manager__c = 'test');
        insert testaccount;
                   
        Opportunity testrenewal =  new Opportunity(accountId = testaccount.Id, Amount = 100.00, Closedate = testdate, Description = 'test', Name = 'test', 
                                                   Stagename = 'Baseline', Probability = 100, Coverage_Start_Date__c = System.today().addDays(-15), Coverage_End_Date__c = System.today().addDays(100));
        insert testrenewal;                 

        ApexPages.StandardController sc1 = new ApexPages.StandardController(testrenewal);
        OpportunitySearchController controller1 = new OpportunitySearchController(sc1);           
        controller1.runQuery();
        controller1.runSearch();
        controller1.toggleSort();
        List<String> stgs = controller1.stages;
        List<String> mgs = controller1.managers;


        Test.stopTest();
    }

 

I can't add the whole debug log to this post, it exceeds 20,000 characters.

But here is the first few lines:

26.0 APEX_CODE,FINE;APEX_PROFILING,FINE;DB,INFO;VALIDATION,INFO;WORKFLOW,FINEST
08:14:13.273 (273648000)|EXECUTION_STARTED
08:14:13.273 (273704000)|CODE_UNIT_STARTED|[EXTERNAL]|01pg00000008W1L|TestOpportunitySearchController.myTest
08:14:13.274 (274195000)|METHOD_ENTRY|[2]|01pg00000008W1L|TestOpportunitySearchController.TestOpportunitySearchController()
08:14:13.275 (275963000)|METHOD_EXIT|[2]|TestOpportunitySearchController
08:14:13.276 (276543000)|DML_BEGIN|[9]|Op:Insert|Type:Account|Rows:1
08:14:13.409 (409996000)|CODE_UNIT_STARTED|[EXTERNAL]|Workflow:Account
08:14:13.425 (425182000)|WF_RULE_EVAL_BEGIN|Assignment
08:14:13.425 (425202000)|WF_RULE_EVAL_BEGIN|Response
08:14:13.425 (425212000)|WF_RULE_EVAL_BEGIN|Workflow
08:14:13.425 (425241000)|WF_CRITERIA_BEGIN|[Account: test 001g0000003XhCq]|Date Change TESTING|01Qg0000000ClQz|ON_ALL_CHANGES
08:14:13.427 (427140000)|WF_RULE_FILTER|[Account : Account Name not equal to null]
08:14:13.427 (427165000)|WF_RULE_EVAL_VALUE|test
08:14:13.427 (427172000)|WF_CRITERIA_END|true
08:14:13.427 (427196000)|WF_SPOOL_ACTION_BEGIN|Workflow
08:14:13.427 (427204000)|WF_ACTION| None
08:14:13.427 (427213000)|WF_RULE_EVAL_BEGIN|Escalation
08:14:13.427 (427218000)|WF_RULE_EVAL_END
08:14:13.427 (427270000)|WF_ACTIONS_END| None
08:14:13.427 (427276000)|CODE_UNIT_FINISHED|Workflow:Account
08:14:13.429 (429626000)|DML_END|[9]
08:14:13.430 (430291000)|DML_BEGIN|[13]|Op:Insert|Type:Opportunity|Rows:1
08:14:13.448 (448595000)|CODE_UNIT_STARTED|[EXTERNAL]|01q6000000004v5|changeOpportunityOwnerIfGoldPartner on Opportunity trigger event BeforeInsert for [new]
08:14:13.449 (449541000)|SOQL_EXECUTE_BEGIN|[4]|Aggregations:0|select profileid from user where id = :tmpVar1
08:14:13.452 (452681000)|SOQL_EXECUTE_END|[4]|Rows:1
08:14:13.453 (453075000)|SOQL_EXECUTE_BEGIN|[5]|Aggregations:0|select ownerid from account where id = :tmpVar1
08:14:13.455 (455012000)|SOQL_EXECUTE_END|[5]|Rows:1
08:14:13.455 (455334000)|SOQL_EXECUTE_BEGIN|[6]|Aggregations:0|select name from profile where id = :tmpVar1
08:14:13.457 (457202000)|SOQL_EXECUTE_END|[6]|Rows:1
08:14:13.697 (457662000)|CUMULATIVE_LIMIT_USAGE
08:14:13.697|LIMIT_USAGE_FOR_NS|(default)|
  Number of SOQL queries: 0 out of 100
  Number of query rows: 0 out of 50000
  Number of SOSL queries: 0 out of 20
  Number of DML statements: 1 out of 150
  Number of DML rows: 1 out of 10000
  Number of script statements: 4 out of 200000
  Maximum heap size: 0 out of 6000000
  Number of callouts: 0 out of 10
  Number of Email Invocations: 0 out of 10
  Number of fields describes: 0 out of 100
  Number of record type describes: 0 out of 100
  Number of child relationships describes: 0 out of 100
  Number of picklist describes: 0 out of 100
  Number of future calls: 0 out of 10

08:14:13.697|TESTING_LIMITS
08:14:13.697|LIMIT_USAGE_FOR_NS|(default)|
  Number of SOQL queries: 3 out of 100
  Number of query rows: 3 out of 50000
  Number of SOSL queries: 0 out of 20
  Number of DML statements: 1 out of 150
  Number of DML rows: 1 out of 10000
  Number of script statements: 6 out of 200000
  Maximum heap size: 0 out of 6000000
  Number of callouts: 0 out of 10
  Number of Email Invocations: 0 out of 10
  Number of fields describes: 0 out of 100
  Number of record type describes: 0 out of 100
  Number of child relationships describes: 0 out of 100
  Number of picklist describes: 0 out of 100
  Number of future calls: 0 out of 10

 

 

logontokartiklogontokartik

Hmm. looks like your code is looking for Current Page parameters and you didnt set them in your test class. Include these lines in your test class before you instantiate your controller class. (immediately after insert testrenewal)

 Pagereference testPage = Page.<your Visualforce page name>;
 Test.setCurrentPagereference(testPage);
 Apexpages.currentPage().getParameters().put('name','test');
 Apexpages.currentPage().getParameters().put('account','test');
 Apexpages.currentPage().getParameters().put('manager','test');         
Apexpages.currentPage().getParameters().put('stage','Baseline');

PS : It would be best practice to generally handle exceptions in your class (maybe using a try catch block)

This was selected as the best answer
GrrrrrrrrrrrrrGrrrrrrrrrrrrr

When I include the text as you indicated, I get this error:

Error: Compile Error: unexpected token: ';' at line 16 column 60, which is this line:

Pagereference testPage = Page.<dynamicRenewalSearch>;

 

So, if I take out the semicolon I get this:

Error: Compile Error: unexpected token: 'Test.setCurrentPageReference' at line 17 column 8

 

Here is the code en total:

 

@isTest(SeeAllData=true)
private with sharing class TestOpportunitySearchController 
{               
    static testMethod void myTest()    
    {                

        Test.startTest();
        date testdate = System.today().addDays(+1);
        Account testaccount = new Account(Name = 'test', Trident_Contract_Manager__c = 'test');
        insert testaccount;
                   
        Opportunity testrenewal =  new Opportunity(accountId = testaccount.Id, Amount = 100.00, Closedate = testdate, Description = 'test', Name = 'test', 
                                                   Stagename = 'Baseline', Probability = 100, Coverage_Start_Date__c = System.today().addDays(-15), Coverage_End_Date__c = System.today().addDays(100));
        insert testrenewal;
        
        Pagereference testPage = Page.<dynamicRenewalSearch>
        Test.setCurrentPageReference(testPage);
        Apexpages.currentPage().getParameters().put('name','test');
        Apexpages.currentPage().getParameters().put('account','test');
        Apexpages.currentPage().getParameters().put('manager','test');         
        Apexpages.currentPage().getParameters().put('stage','Baseline');
        Apexpages.currentPage().getParameters().put('closedate',system.today());  
                     
        ApexPages.StandardController sc1 = new ApexPages.StandardController(testrenewal);
        OpportunitySearchController controller1 = new OpportunitySearchController(sc1);           
        controller1.runQuery();
        controller1.runSearch();
        controller1.toggleSort();
        List<String> stgs = controller1.stages;
        List<String> mgs = controller1.managers;

        Test.stopTest();
    }
}

 

Unfortunately, I am not very good at Apex / VF (or programming) yet.  So I am not sure how to do a try / catch block.  I understand that they are for catching errors, but syntactically, I havent figured it out, or how to use it.

 

GrrrrrrrrrrrrrGrrrrrrrrrrrrr

WoW!

So, thye problem was I had to remove the brackets < > (silly me!) and to alter the closedate to a string, and VOILA!

100% coverage!

 

Thank you

@isTest(SeeAllData=true)
private with sharing class TestOpportunitySearchController 
{               
    static testMethod void myTest()    
    {                

        Test.startTest();
        date testdate = System.today().addDays(+1);
        Account testaccount = new Account(Name = 'test', Trident_Contract_Manager__c = 'test');
        insert testaccount;
                   
        Opportunity testrenewal =  new Opportunity(accountId = testaccount.Id, Amount = 100.00, Closedate = testdate, Description = 'test', Name = 'test', 
                                                   Stagename = 'Baseline', Probability = 100, Coverage_Start_Date__c = System.today().addDays(-15), Coverage_End_Date__c = System.today().addDays(100));
        insert testrenewal;
        
        Pagereference testPage = Page.dynamicRenewalSearch;
        Test.setCurrentPageReference(testPage);
        Apexpages.currentPage().getParameters().put('name','test');
        Apexpages.currentPage().getParameters().put('account','test');
        Apexpages.currentPage().getParameters().put('manager','test');         
        Apexpages.currentPage().getParameters().put('stage','Baseline');
        Apexpages.currentPage().getParameters().put('closedate','12/10/2020');  
                            
        ApexPages.StandardController sc1 = new ApexPages.StandardController(testrenewal);
        OpportunitySearchController controller1 = new OpportunitySearchController(sc1);           
        controller1.runQuery();
        controller1.runSearch();
        controller1.toggleSort();
        List<String> stgs = controller1.stages;
        List<String> mgs = controller1.managers;

        Test.stopTest();
    }
}

 

logontokartiklogontokartik

Glad I could help.