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
neeruneeru 

Test class for this apex class

Hi All,

i am new to testclasses i dont know how to write test classes exactly...but i am tried but i am geting 80% code coverage only..but i need 100% can any one help this please??

 

 

 

public with sharing class accounts_based_on_months
{
 
   public String selected_month { get; set; }
   public list<account>acc;
   public list<account>accounts;
   

   public PageReference getrecords()
   {
        string dat='';
         accounts=new list<account>();
         //acc.clear();
        acc=new list<account>();
        acc=[select id,Createddate,name,phone from account];
        for(account a:acc)
        {
            dat=a.Createddate.format('MMMM');
            
            if(selected_month ==dat)
            {
              accounts.add(a);
             }
            
        }
       return null;
   }


   public list<account> getAccounts()
   {
     
           return accounts;
   }
}

 

thanks,

bhagi

Best Answer chosen by Admin (Salesforce Developers) 
colemabcolemab

Right.  The account isn't being added because selected_month hasn't been set.  Try this:

 

static testMethod Void Testaccounts_based_on_months() {
     // create some accounts to test with
     Account MyAccount = new Account(Name='Test Account 1');
     insert MyAccount;

     MyAccount = new Account(Name='Test Account 2');
     insert MyAccount;

     accounts_based_on_months MyObject = new accounts_based_on_months();

// set the selected month to this month so it will match the created date's month
MyObject.selected_month = DateTime.Now().format('MMMM');
MyObject.getrecords(); MyObject.getAccounts(); } // end test class

 

All Answers

colemabcolemab
static testMethod Void Testaccounts_based_on_months() {

     accounts_based_on_months MyObject = new accounts_based_on_months();
     MyObject.getrecords();
MyObject.getAccounts();
} // end test class

 This isn't a full test because you need to insert some accounts before calling the methods.  Even then it would just be a smoke test but it should get you started.

neeruneeru

Thnx for your replay colemab

 

 

i am also writing same thing just create instance of class and calling methods of my class for that i am getting 80 % code coverage,,

 

but i dont know how to write class logic in my test class

can you write my class logic for test class please

colemabcolemab

Here is a better test class.  Just understand that if you have any custom validation rules, you may need to modify the test data to meet them or you will get an exception while running the test.

 

static testMethod Void Testaccounts_based_on_months() {
     // create some accounts to test with
Account MyAccount = new Account(Name='Test Account 1');
insert MyAccount;

MyAccount = new Account(Name='Test Account 2');
insert MyAccount;

// test logic - use starttest to reset any limits
Test.startTest();
accounts_based_on_months MyObject = new accounts_based_on_months(); MyObject.getrecords(); MyObject.getAccounts();

Test.stopTest(); } // end test class

 

neeruneeru

when i compiled with test.starttest(),test.stoptest() it throws errors....when i remove these methods after the test class is saved and giving code coverage 92%...colemab

but its not giving 100%..what shall i do??

colemabcolemab

Those statements aren't strictly required so drop them if you want.

 

When you say you don't get 100% coverage, is that the total coverage?  Or is that just the coverage on the class? They are different.

 

It is most likely that you are getting 100% coverage on the class but not in the system - i.e. you have other code out side of this class in the system that this class doesn't provide test coverage for and you averaging out to 92%.

 

100% coverage is not required to deploy to production - only 75% is required.

 

If you aren't getting 100% coverage on the class:

Scroll down to the class in the list and click on the text of the percentage (i.e. where it says 92%) and after a couple second delay, it should open a new window that will show which lines got code coverage (they will be highlighted in red).   Please reply back and paste the line(s) that don't have coverage.

neeruneeru

 

 

it shows the red line below statement...i think accounts are not added to list..

 

accounts.add(a);

colemabcolemab

Right.  The account isn't being added because selected_month hasn't been set.  Try this:

 

static testMethod Void Testaccounts_based_on_months() {
     // create some accounts to test with
     Account MyAccount = new Account(Name='Test Account 1');
     insert MyAccount;

     MyAccount = new Account(Name='Test Account 2');
     insert MyAccount;

     accounts_based_on_months MyObject = new accounts_based_on_months();

// set the selected month to this month so it will match the created date's month
MyObject.selected_month = DateTime.Now().format('MMMM');
MyObject.getrecords(); MyObject.getAccounts(); } // end test class

 

This was selected as the best answer
neeruneeru

Hi Colemab

 

      i came across a situation where i need to create pageblocktable  many times so i want to create a component which will create pageblock table dynamically i have this idea how to resolve it...

 

My Approch is

 

Here i am retrieving the object id from the url in visualforce page through object id i have the code to retrieve the object name and fields of that object dynamically...and also i retrieving the records through dynamic soql.....But i stuck How to Display These Records in PageBlockTable......

 

help me out in this scenario colemab...

 

visualforce page:

<apex:page >
          <c:Dynamicpbt objId="{!$Currentpage.parameters.id}"/> 
</apex:page>

                 // here we get the object from url dynamically through objid....

 

Component:

 

<apex:component controller="dynamicpbt">
  <apex:attribute name="objId" type="String" description="The id of the object to which PBT for" required="true" assignTo="{!sobjId}"/>
   <apex:form id="PBTForm">
    <apex:pageBlock title="DYNAMICPBT">
    </apex:pageBlock>
   </apex:form>
</apex:component>
 
Controller Logic:
 
//this code retrives the fields name ,Object names  dynamically
 
List<Schema.SObjectType> gd = Schema.getGlobalDescribe().Values();
Map<String,String> objectMap = new Map<String,String>();
for(Schema.SObjectType f : gd)
{
     objectMap.put(f.getDescribe().getKeyPrefix(), f.getDescribe().getName());
}
 
String sampleId ='00390000003LIVw';(//here we can pass objctid through objid)
String prefix =  sampleId.substring(0,3);
String objectName = objectMap.get(prefix);
System.debug('** SObject Name ** '+objectName);
 
Map<String, Schema.SObjectField> desResult = Schema.getGlobalDescribe().get(objectName).getDescribe().Fields.getMap();
List<String> fieldList = new List<String>();
fieldList.addAll(desResult.keySet());
for(integer i =0;i<fieldList.size();i++)
{
    System.debug('** Field Name ** '+fieldList[i]);
 
}
 
 
along these we can write a dynamic soql query to retrieve the records ...i'm stuck here to bind these records to component to disply in pageblock table
 
String soqlquery = 'Select '+fieldlist+' from '+objectname+' ';
        // Run the query
        queryresult = Database.query(soqlquery);
        return queryresult;
 
 
Thanks,
neeru
 

 

colemabcolemab

Please start a new thread for your page block issue.  This will help keep the current thread and the new thread on topic for those that are searching.