+ Start a Discussion
Nishad BashaNishad Basha 

How write the Test class for Account of contacts in salesforce

Prafull G.Prafull G.
Test classes are required for Apex Class and Apex Triggers. Do you have specific code related to Account/Contact.
Could you explain little more so we can help. 

Cheers!
Nishad BashaNishad Basha
yes, Prafull G.
please  check this code
ublic class MyAccountcreation{
public static List<Account> createacc(){
List<Account> acc = new List<Account>([SELECT CreatedbyID,Account.Name,(SELECT name,Contact.FirstName, Contact.LastName FROM Account.Contacts) FROM Account]); 
       system.debug(acc);
     
        
         
     for (Account ac : acc) { 
     system.debug(ac); 
  }
    return acc;    
}
}

 
Nishad BashaNishad Basha

Hi, Prafull G.
How to write the Test class for  above apex class. please give some ideas.
Amit Chaudhary 8Amit Chaudhary 8
Please check below blog how to write the test classes in salesforce
http://amitsalesforce.blogspot.in/2015/06/best-practice-for-test-classes-sample.html
Test Class for Trigger
@isTest 
public class TriggerTestClass 
{
    static testMethod void testMethod1() 
 {
  // Perform DML here only
 
        }
}
Test Class for Standard Controller
@isTest 
public class ExtensionTestClass 
{
 static testMethod void testMethod1() 
 {
 Account testAccount = new Account();
 testAccount.Name='Test Account' ;
 insert testAccount;

 Test.StartTest(); 
  ApexPages.StandardController sc = new ApexPages.StandardController(testAccount);
  myControllerExtension testAccPlan = new myControllerExtension(sc);

  PageReference pageRef = Page.AccountPlan; // Add your VF page Name here
  pageRef.getParameters().put('id', String.valueOf(testAccount.Id));
  Test.setCurrentPage(pageRef);

  //testAccPlan.save(); call all your function here
 Test.StopTest();
 }
}
Test Class for Controller class
@isTest 
public class ControllerTestClass 
{
 static testMethod void testMethod1() 
 {
 Account testAccount = new Account();
 testAccount.Name='Test Account' ;
 insert testAccount;

 Test.StartTest(); 

  PageReference pageRef = Page.AccountPlan; // Add your VF page Name here
  pageRef.getParameters().put('id', String.valueOf(testAccount.Id));
  Test.setCurrentPage(pageRef);

  myController testAccPlan = new myController();
  
  //testAccPlan.save(); call all your function here
 Test.StopTest();
 }
}
Please follow below salesforce Best Practice for Test Classes :-

1. Test class must start with @isTest annotation if class class version is more than 25
2. Test environment support @testVisible , @testSetUp as well
3. Unit test is to test particular piece of code working properly or not .
4. Unit test method takes no argument ,commit no data to database ,send no email ,flagged with testMethod keyword .
5. To deploy to production at-least 75% code coverage is required
6. System.debug statement are not counted as a part of apex code limit.
7. Test method and test classes are not counted as a part of code limit
9. We should not focus on the  percentage of code coverage ,we should make sure that every use case should covered including positive, negative,bulk and single record .
Single Action -To verify that the the single record produces the correct an expected result .
Bulk action -Any apex record trigger ,class or extension must be invoked for 1-200 records .
Positive behavior : Test every expected behavior occurs through every expected permutation , i,e user filled out every correctly data and not go past the limit .
Negative Testcase :-Not to add future date , Not to specify negative amount.
Restricted User :-Test whether a user with restricted access used in your code .10. Test class should be annotated with @isTest .
11 . @isTest annotation with test method  is equivalent to testMethod keyword .
12. Test method should static and no void return type .
13. Test class and method default access is private ,no matter to add access specifier .
14. classes with @isTest annotation can't be a interface or enum .
15. Test method code can't be invoked by non test request .
16. Stating with salesforce API 28.0 test method can not reside inside non test classes .
17. @Testvisible annotation to make visible private methods inside test classes.
18. Test method can not be used to test web-service call out . Please use call out mock .
19. You can't  send email from test method.
20.User, profile, organization, AsyncApexjob, Corntrigger, RecordType, ApexClass, ApexComponent ,ApexPage we can access without (seeAllData=true) .
21. SeeAllData=true will not work for API 23 version eailer .
22. Accessing static resource test records in test class e,g List<Account> accList=Test.loadData(Account,SobjectType,'ResourceName').
23. Create TestFactory class with @isTest annotation to exclude from organization code size limit .
24. @testSetup to create test records once in a method  and use in every test method in the test class .
25. We can run unit test by using Salesforce Standard UI,Force.com IDE ,Console ,API.
26. Maximum number of test classes run per 24 hour of period is  not grater of 500 or 10 multiplication of test classes of your organization.
27. As apex runs in system mode so the permission and record sharing are not taken into account . So we need to use system.runAs to enforce record sharing .
28. System.runAs will not enforce user permission or field level permission .
29. Every test to runAs count against the total number of DML issued in the process .


Please let us know if this post will help you

Thanks
Amit Chaudhary
Amit Chaudhary 8Amit Chaudhary 8
Please try below test class. I hope that will help u.
@isTest 
public class MyAccountcreationTest 
{
	static testMethod void testMethod1() 
	{
		Account testAccount = new Account();
		testAccount.Name='Test Account' ;
		insert testAccount;
		
		Contact cont = new Contact();
		cont.FirstName='Test';
		cont.LastName='Test';
		cont.Accountid= testAccount.id;
		insert cont;
		
		Test.StartTest(); 
			MyAccountcreation obj = new MyAccountcreation();
			List<Account> lstAcc = obj.createacc();
			
		Test.StopTest();
	}
}
Please let us know if above class will help u

Thanks,
Amit Chaudhary
Salesforce seekarSalesforce seekar
hi amit , 

may i know what are you calling here 
List<Account> lstAcc = obj.createacc(); 

what is createacc ??? 
Amit Chaudhary 8Amit Chaudhary 8
createacc is a static method in MyAccountcreation class
ublic class MyAccountcreation{
public static List<Account> createacc(){
List<Account> acc = new List<Account>([SELECT CreatedbyID,Account.Name,(SELECT name,Contact.FirstName, Contact.LastName FROM Account.Contacts) FROM Account]); 
       system.debug(acc);
     
        
         
     for (Account ac : acc) { 
     system.debug(ac); 
  }
    return acc;    
}
}

 
Salesforce seekarSalesforce seekar
hi Amit , 

I am new bie for writing test classes need your help here , can you guide  me please  to write a test class for below code . . 

the below controller displays related contacts for accounts. 
my controller : 
public with sharing class AccRelatedCont 
{
    public string selectedAccountId{get; set;}
    public List<Account> accounts{get; set;}
    public List<Contact> contacts{get; set;}
   
    public AccRelatedCont ()
    {
        accounts = [SELECT Name, Type FROM Account LIMIT 20];
    }
    public PageReference getSelected()
    {
        System.debug('Entered account selection block');
        selectedAccountId = ApexPages.currentPage().getParameters().get('accid');
        //above accid is passing as paramaeter for VF page . 
        contacts = new List<Contact>();
        return null;
    }
    public void viewContacts()
    {  
        if(selectedAccountId != null)
        {
            contacts = [SELECT FirstName, LastName FROM Contact WHERE AccountId =:selectedAccountId];
            if(contacts.size() == 0)
            contacts = null;
        }
    }
}


my vf page : 
<apex:page controller="AccRelatedCont" > <apex:form > <!-- Account page block --> <apex:pageBlock title="Account Viewer" > <apex:pageblockSection rendered="{!If(accounts !=null && accounts.size>0,true,false)}"> <apex:pageBlockTable value="{!accounts}" var="acc" width="100%" id="accTable"> <apex:column headerValue="Select"> <input type="radio" name="<strong>selectRadio</strong>" id= "radio"> <br/> <apex:actionSupport event="onclick" action="{!getSelected}" status="buttonStatus" reRender="cntblock"> <apex:param name="accid" value="{!acc.id}"/> </apex:actionSupport> </input> </apex:column> <apex:column value="{!acc.Name}"/> <apex:column value="{!acc.Type}"/> </apex:pageBlockTable> </apex:pageBlockSection> <!-- Action status block --> <apex:actionStatus id="buttonStatus"> <apex:facet name="start"> <apex:outputPanel > <apex:commandButton value="View Contact Records" disabled="true"/> </apex:outputPanel> </apex:facet> <apex:facet name="stop"> <apex:outputPanel > <apex:commandButton value="View Contact Records" action="{!viewContacts}" reRender="cntblock"/> </apex:outputPanel> </apex:facet> </apex:actionStatus> </apex:pageBlock> <!-- Contact Block --> <apex:outputPanel id="cntblock"> <apex:pageBlock title="Available Contacts" rendered="{!If(contacts != null && contacts.size>0,true,false)}"> <apex:pageblockSection > <apex:pageBlockTable value="{!contacts}" var="con" width="100%" id="cntTable"> <apex:column value="{!con.FirstName}"/> <apex:column value="{!con.LastName}"/> </apex:pageBlockTable> </apex:pageblockSection> </apex:pageBlock> <apex:pageMessage summary="No Contacts Found" severity="Info" strength="3" rendered="{!AND(contacts == null, selectedAccountId != null)}"/> </apex:outputPanel> </apex:form> </apex:page>

 
Amit Chaudhary 8Amit Chaudhary 8
Hi

Please start new thread of this issue
@isTest 
public class AccRelatedContTest 
{
	static testMethod void testMethod1() 
	{
		Account testAccount = new Account();
		testAccount.Name='Test Account' ;
		insert testAccount;
		
		Contact cont = new Contact();
		cont.FirstName='Test';
		cont.LastName='Test';
		cont.Accountid= testAccount.id;
		insert cont;
		
		Test.StartTest(); 
			AccRelatedCont  obj = new AccRelatedCont();
			obj.getSelected();
			obj.selectedAccountId = testAccount.id;
			obj.viewContacts();
			
		Test.StopTest();
	}
}
Try above code and let us know if this will help you

 
div ninediv nine
How to write test class for this code. Thanks
public class apex {
public account acc {get;set;}

public apex(){

account acc = [select name from account limit 1];

}
}
Arpit Gupta 62Arpit Gupta 62
sir 17 line show me error found
 
Maaz uddinMaaz uddin
Hi, may be your handler class is static
Nishad BashaNishad Basha
1. Consider there are 3 users U1(Role R1, Profile P1), U2(Role R2, Profile P2) and U3(Role R3, Profile P3) and all these 3 users have Read permission on Lead object granted by their respective profiles. Organization Wide Defaults (OWD) is set to Private. (2 Marks) With above setup, can user U1 access Lead records of U2 and U3? a) Yes, user U1 can access Lead records of U2 and U3. b) No, user U1 cannot access Lead records of U2 and U3. With above setup, there is a requirement where all these 3 users need Edit access to all Lead records which belong to country India.