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
Srujana D 7Srujana D 7 

Hi, I'm trying to write a test class for the below:

apex class:
public class myAccount {
    private final contact con;
    public string filename{set;get;}
    public string contenttype {set;get;}
    public string Conlastname{get;set;}
    public string conphone{get;set;}
    public string conemail{get;set;}
    public string Conmobilephone{get;set;}
    public string Accid='';
    public blob Photo{get;set;}
    public string photoname{get;set;}
    public string photourl{get;set;}
    //Contstructor 
   public myAccount(ApexPages.StandardController controller) {
     con=(Contact)controller.getRecord();
    }
   
    //this method updates the Contact with photourl and insert The Attachment Record
    public void UploadPhoto(){
        try{
            con.lastname = conlastname;  
            con.email = conemail;
            con.phone = conphone;
            con.mobilephone = conmobilephone;
            insert con;
           // Accid = ApexPages.currentPage().getParameters().get('id');  
           // inserting attachement with Attached photo      
            Attachment objA=new Attachment();
            objA.body = photo;
            objA.name = filename;
            objA.parentid= con.id;
            objA.ContentType = contenttype;
            insert objA;
           
            string Attid= objA.id;
            string attachmentid=Attid.substring(0,15);
             system.debug(Attid);
             con.imageUrl__c = '<img src="https://hyundaycars-dev-ed--c.ap5.content.force.com/servlet/servlet.FileDownload?file='+attachmentid+'"></img>';
           con.urlToImage__c = 'https://hyundaycars-dev-ed--c.ap5.content.force.com/servlet/servlet.FileDownload?file='+attachmentid;
            update con;
            photourl = con.urlToImage__c ;        
        }catch(Exception e){
            system.debug('Exception message'+e);
        }
     } 
     public List<SelectOption> getTypes(){
            Schema.sObjectType sobject_type = Contact.getSObjectType();
            Schema.DescribeSObjectResult sobject_describe = sobject_type.getDescribe();
            Map<String, Schema.SObjectField> field_map = sobject_describe.fields.getMap();
            List<Schema.PicklistEntry> pick_list_values = field_map.get('Level__c').getDescribe().getPickListValues();
            List<selectOption> options = new List<selectOption>();
           for (Schema.PicklistEntry a : pick_list_values) {
                      options.add(new selectOption(a.getLabel(), a.getValue()));
          }
      return options;
}
 public List<SelectOption> getTypes1(){
            Schema.sObjectType sobject_type = Contact.getSObjectType();
            Schema.DescribeSObjectResult sobject_describe = sobject_type.getDescribe();
            Map<String, Schema.SObjectField> field_map = sobject_describe.fields.getMap();
            List<Schema.PicklistEntry> pick_list_values = field_map.get('select_multipl__c').getDescribe().getPickListValues();
            List<selectOption> options = new List<selectOption>();
           for (Schema.PicklistEntry a : pick_list_values) {
                      options.add(new selectOption(a.getLabel(), a.getValue()));
          }
      return options;
}
}
Test class:
@isTest
public class TestmyAccount {
    @isTest static void myAccountTest(){
        Contact c = new Contact(LastName='lastName1');
            insert c;
        Attachment objA=new Attachment();
            objA.body = Blob.valueOf('photourl');
            objA.Name = 'filename';
            objA.parentid= c.id;
            objA.ContentType = 'Applications';
            insert objA;
        string ids = objA.Id;
            c.imageUrl__c = 'imageurl';
            c.urlToImage__c = 'photourl';
            update c;
        Test.startTest();
            myAccount acc =new myAccount(new ApexPages.StandardController(c));
       /* ApexPages.StandardController sc = new ApexPages.StandardController(c);
        myAccount acc = new myAccount(sc);*/
        acc.UploadPhoto();
        List<Attachment> attachments=[select id, name from Attachment where parent.id=:c.id];
        System.assertEquals(1, attachments.size());

        acc.Photo=Blob.valueOf('photourl');
        acc.filename='filename';
        acc.contenttype='Applications';
        acc.photoname='photoname';
        acc.photourl='photourl';
        
        List<SelectOption> sel = acc.getTypes();
        List<SelectOption> selist = acc.getTypes1();
        Test.stopTest();
    }
}
Best Answer chosen by Srujana D 7
sfdcMonkey.comsfdcMonkey.com
HI Sur
try following test class this will give you more then 95% code coverge :
@isTest
public class myAccountTest {
    static testmethod void demoMethod(){
          contact cc = new contact();
          cc.lastName = 'test123';
          
        ApexPages.StandardController sc = new ApexPages.StandardController(cc);
        
        myAccount obj = new myAccount(sc);
        obj.Photo = Blob.valueOf('Unit Test Attachment Body');
        obj.filename = 'test';
        obj.contenttype = 'text/html';
        obj.photoname = 'test';
        obj.photourl = 'test';
        obj.Conlastname = 'https://google.com';
        
        obj.UploadPhoto();
        obj.getTypes();
        obj.getTypes1();
        
      }
        
    
}

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

Thanks let us know if it helps you

All Answers

Raj VakatiRaj Vakati
Use this code
 
@istest
public class apexTest
{
    static testMethod void validateSearch(){
        Test.startTest();
        
        
        Account acct = new Account(
            name = 'Test Account'
        );
        insert acct;
        
        Contact cont = new Contact(
            accountId = acct.id,
            firstName = 'Test',
            lastName = 'Contact',
            title = 'Test'
        );
        insert cont;
        Attachment objA=new Attachment();
        objA.body = Blob.valueOf('photourl');
        objA.Name = 'filename';
        objA.parentid= cont.id;
        objA.ContentType = 'Applications';
        insert objA;
        
        
        
        ApexPages.StandardController sc = new ApexPages.StandardController(cont);
        myAccount doSe=new myAccount(sc);
        doSe.filename='Test FIle';
        doSe.contenttype ='text/html';
        doSe.Photo=Blob.valueOf('Name') ;
        doSe.photoname='Tets';
        doSe.photourl='https://google.com';
        
        
        doSe.getTypes();
        doSe.getTypes1();
        
        doSe.UploadPhoto();
        
        
        
    }
    
}

 
sfdcMonkey.comsfdcMonkey.com
HI Sur
try following test class this will give you more then 95% code coverge :
@isTest
public class myAccountTest {
    static testmethod void demoMethod(){
          contact cc = new contact();
          cc.lastName = 'test123';
          
        ApexPages.StandardController sc = new ApexPages.StandardController(cc);
        
        myAccount obj = new myAccount(sc);
        obj.Photo = Blob.valueOf('Unit Test Attachment Body');
        obj.filename = 'test';
        obj.contenttype = 'text/html';
        obj.photoname = 'test';
        obj.photourl = 'test';
        obj.Conlastname = 'https://google.com';
        
        obj.UploadPhoto();
        obj.getTypes();
        obj.getTypes1();
        
      }
        
    
}

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

Thanks let us know if it helps you
This was selected as the best answer
Srujana D 7Srujana D 7
Tq Piyush.I got 98%