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
Daniel GageDaniel Gage 

Can't get the Test Case to right to get any coverage.

Can't get any coverage on this, and can't figure out why. Both this class and the test cases were written by another developer (who is not available anymore to ask questions of). But I can't get any coverage on this no matter what I try. Any help is greatly appreciated.

Going to have to put this code up in parts as it is too large.
public without sharing class MyProfileController {
    public String fname{set;get;}
    public String lname{set;get;}
    public String fullmiddelname{set;get;}
    public String pemail{set;get;}
    public String semail{set;get;}
    public String mobile{set;get;}
    public String home{set;get;}
    public String work{set;get;}
    public String street{set;get;}
    public String city{set;get;}
    public String state{set;get;}
    public String zip{set;get;}
    public String country{set;get;}
    public String facebook{set;get;}
    public String twitter{set;get;}
    public String linkedin{set;get;}
    public String birthdate{set;get;}
    public String gender{set;get;}
    public String race{set;get;}
    public String profession{set;get;}
    public String pinterest{set;get;}
    public String ainterest{set;get;}    
    public String ointerest{set;get;}    
    public String corpregion{set;get;}
    public String alumniregion{set;get;}
    public String corpregionView{set;get;}
    public String alumniregionView{set;get;}
    public String corpYear{set;get;}
    public boolean HasOptedOutOfEmail{get;set;}
    public boolean DoNotCall{get;set;}
    public boolean memberoptout{set;get;}
    public List<SelectOption> corpRegions{get;set;}
    public List<SelectOption> advocacyInterests{get;set;}
    public List<SelectOption> policyInterests{get;set;}
    public List<SelectOption> organizingInterests{get;set;}
    public List<SelectOption> ethnicityOntions{get;set;}
    public blob imagebody{set;get;}
    public string imageName{set;get;}
    public string imagesrc{set;get;}
    public string imagesrc1{set;get;}
    public boolean isEditable{set;get;}
    public boolean registered{set;get;}
    public String leadership{set;get;}
    public List<SelectOption> leaderships{get;set;}
    public List<SelectOption> volunteerInterests{get;set;}
    public String volunteerInterest{set;get;}
    List<Region__c> corpRegionsList;
    List<Region__c> alumniRegionsList;
    Map<String,Region__c> regionsMap;
    String oldZip;
    String contactId;
    List<Attachment> att;
    public Contact con{set;get;}
    Attachment img;
    Contact_Picture__c contactImage;
    public LEE_Campaign__c leecamp{set;get;}
    public boolean showErr{set;get;}
    List<Region_ZipCode__c> zipcodes;
    List<Region_Membership__c> regionMembers;
    Decimal filesize;
    public boolean isError{set;get;}
    public String errorMsg{set;get;}
    public string title{set;get;}
    public string employer{set;get;}
    public MyProfileController(){
        isError = false;
        regionsMap = new Map<String,Region__c>();
        leecamp = new LEE_Campaign__c();
        showErr = false;
        User loggedUser = [SELECT id,ContactID from User WHERE Id=: userInfo.getUserId()];
        //contactId = ApexPages.currentPage().getParameters().get('id');
        contactId = loggedUser.ContactId;
       // contactId = '003M000000Dp9z9';
        isEditable = false;
        policyInterests =  new List<SelectOption>();
        advocacyInterests = new List<SelectOption>();
        organizingInterests = new List<SelectOption>();
        ethnicityOntions = new List<SelectOption>();
        leaderships = new List<SelectOption>();
        volunteerInterests  = new List<SelectOption>();
        //Populate Advocacy Interest Picklist
        Schema.DescribeFieldResult fieldResult = Contact.Advocacy_Interest__c.getDescribe();
        List<Schema.PicklistEntry> ple = fieldResult.getPicklistValues();
        for(Schema.PicklistEntry f : ple){
            advocacyInterests.add(new SelectOption(f.getLabel(), f.getValue()));
        }
        //Populate Policy Interest Picklist
        fieldResult =  Contact.Policy_Interest__c.getDescribe();
        ple = fieldResult.getPicklistValues();
        for(Schema.PicklistEntry f : ple){
            policyInterests.add(new SelectOption(f.getLabel(), f.getValue()));
        }
        
        //Populate Organizing Interest Picklist
        fieldResult =  Contact.Organizing_Interest__c.getDescribe();
        ple = fieldResult.getPicklistValues();
        for(Schema.PicklistEntry f : ple){
            organizingInterests.add(new SelectOption(f.getLabel(), f.getValue()));
        }
        //Populate Ethnicity Picklist
        fieldResult =  Contact.Ethnicity__c.getDescribe();
        ple = fieldResult.getPicklistValues();
        for(Schema.PicklistEntry f : ple){
            ethnicityOntions.add(new SelectOption(f.getLabel(), f.getValue()));
        }
        
        //Populate Public Leadership Aspirations Picklist
        fieldResult =  Contact.Public_Leadership_Aspirations__c.getDescribe();
        ple = fieldResult.getPicklistValues();
        for(Schema.PicklistEntry f : ple){
            leaderships.add(new SelectOption(f.getLabel(), f.getValue()));
        }
        //Populate Volunteer Interests Picklist
        fieldResult =  Contact.Volunteer_Interests__c.getDescribe();
        ple = fieldResult.getPicklistValues();
        for(Schema.PicklistEntry f : ple){
            volunteerInterests.add(new SelectOption(f.getLabel(), f.getValue()));
        }
        
        //contactId = ApexPages.currentPage().getParameters().get('contactId');
        corpRegions = new List<SelectOption>();
        corpRegionsList = [SELECT id,Name from Region__c];
        //Populate Corp Region and Amumni Region Picklist
        if(corpRegionsList != null && corpRegionsList.size() > 0){
            for(Region__c r: corpRegionsList){
                corpRegions.add(new SelectOption(r.Id,r.Name));
                regionsMap.put(r.Name,r);
            }
        }else{
            corpRegions.add(new SelectOption('',''));
        }
        
        if(contactId != null && contactId.trim().length() > 0){
            con = [Select c.Twitter__c,  c.Secondary_Email__c,
                        c.Ethnicity__c, c.Profession__c, c.Policy_Interest__c, Volunteer_Interests__c,
                        c.Phone,  c.Organizing_Interest__c, c.Name, c.MobilePhone, c.Member_Stage__c,
                        c.MailingStreet, c.MailingState, c.MailingPostalCode, c.MailingCountry, c.MailingCity, c.DoNotCall,
                        c.Linked_In__c, c.LeadSource, c.LastName,  c.Id, c.HomePhone, Registered_to_Vote__c,
                        c.Gender__c, c.Full_Middle_Name__c, c.FirstName, c.Fax, c.Facebook__c, Public_Leadership_Aspirations__c,
                        c.Email,c.Corps_Year__c, c.Corp_Region__c, c.Birthdate, c.Alumni_Region__c, c.Advocacy_Interest__c, c.HasOptedOutOfEmail,
                        c.Employee_Title__c,c.Employment_Organization__c
                    From Contact c
                    WHERE Id=: contactId];
                    
            if(con != null){
                fname = con.FirstName;
                lname = con.LastName;
                fullmiddelName = con.Full_Middle_Name__c;
                home = con.HomePhone;
                mobile = con.MobilePhone;
                work = con.Phone;
                pemail = con.Email;
                semail = con.Secondary_Email__c;
                facebook = con.Facebook__c;
                twitter = con.Twitter__c;
                linkedin = con.Linked_In__c;
                street = con.MailingStreet;
                city = con.MailingCity;
                state = con.MailingState;
                zip = con.MailingPostalCode;
                oldZip = zip;
                country = con.MailingCountry;
                title = con.Employee_Title__c;
                employer = con.Employment_Organization__c;
                //birthdate = String.valueOf(con.BirthDate);
                race = con.Ethnicity__c;
                profession = con.Profession__c;
                gender = con.Gender__c;
                pinterest = con.Policy_Interest__c;
                ainterest = con.Advocacy_Interest__c;
                ointerest = con.Organizing_Interest__c;
                corpregion = con.Corp_Region__c;
                alumniregion = con.Alumni_Region__c;
                if(con.HasOptedOutOfEmail != null)
                    HasOptedOutOfEmail = con.HasOptedOutOfEmail;
                else
                    HasOptedOutOfEmail = false;
                if(con.DoNotCall != null)
                    DoNotCall = con.DoNotCall;
                else
                    DoNotCall = false;
                for(SelectOption so:corpRegions){
                    if(so.getValue() == corpregion){
                        corpregionView = so.getLabel();
                    }
                }
                
                for(SelectOption so:corpRegions){
                    if(so.getValue() == alumniregion){
                        alumniregionView = so.getLabel();
                    }
                }
                corpYear = con.Corps_Year__c;
                if(con.Member_Stage__c == 'Deactivated'){
                    memberoptout = true;
                }else{
                    memberoptout = false;
                }
                registered = con.Registered_to_Vote__c;
                String str = con.Public_Leadership_Aspirations__c;
                
                /*str = str.replaceAll(';',',');
                str ='['+str + ']';*/
                leadership = str;
                System.Debug('@@@@@@@@Value'+leadership);
                volunteerInterest = con.Volunteer_Interests__c;
                
                List<Contact_Picture__c> contactImages = [SELECT id,Contact__c from Contact_Picture__c WHERE Contact__c =: con.id];
                if(contactImages != null && contactImages.size() >0){
                    contactImage = contactImages[0];
                    att = [SELECT id,Name from Attachment WHERE parentId =: contactImage.Id Order By CreatedDate Desc LIMIT 1];
                    if(att != null && att.size() > 0){
                        System.Debug('######Attachment ID'+att[0].id);
                        //imagebody = att[0].body;
                       /* imagesrc1 = String.valueOf(imagebody);
                        System.Debug('######Image Body'+imagesrc1);*/
                        //imageName = att[0].Name;
                        imagesrc = '/servlet/servlet.FileDownload?file='+att[0].id;
                    }
                }
                
            }else{
                con = new Contact();
            }
        }
    }
    public void upload(){       
        if(imageName != null && imageBody != null){
            filesize = imageBody.size();
            filesize = filesize /(1024*1024);
            if(filesize <= 1){
                if(con != null && con.id != null){
                    if( contactImage != null && contactImage.Contact__c != null){
                        img = new Attachment(Name = imageName,Body=imageBody,ParentId = contactImage.id);
                        insert img;
                    }else{
                        contactImage = new  Contact_Picture__c(Contact__c = con.Id);
                        insert contactImage;
                        img = new Attachment(Name = imageName,Body=imageBody,ParentId = contactImage.id);
                        insert img;
                    }
                    imagesrc = '/servlet/servlet.FileDownload?file='+img.id;
                    imageBody = null;
                    img = null;
                    isError = false;
                }
            }else{
                isError = true;
                errorMsg = 'File Size can not be more than 1 MB';
                //ApexPages.addMessage(new ApexPages.message(ApexPages.severity.ERROR, 'File Size can not be more than 1 MB'));
                imageBody = null;
                return;
            }
        }
    }

 
Best Answer chosen by Daniel Gage
Roy LuoRoy Luo
System.runAs(user){
    PageReference p = Page.YourVfPage;
    Test.setCurrentPage(p); 
    MyProfileController ctrl = new MyProfileController();
    ctrl.edit();
    ctrl.cancel();
    ctrl.save();
    
}
PS. see https://developer.salesforce.com/forums/ForumsMain?id=906F0000000Aoss

All Answers

Daniel GageDaniel Gage
    public PageReference save(){
        try{
            con.FirstName = fname;
            con.LastName=lname;
            con.Full_Middle_Name__c = fullmiddelName;
            con.HomePhone = home;
            con.MobilePhone = mobile;
            con.Phone = work;
            con.Email = pemail;
            con.Secondary_Email__c = semail;
            con.Facebook__c = facebook;
            con.Twitter__c = twitter;
            con.Linked_In__c = linkedin;
            con.MailingStreet = street;
            con.MailingCity = city;
            con.MailingState = state;
            con.MailingPostalCode = zip;
            con.HasOptedOutOfEmail = HasOptedOutOfEmail;
            con.DoNotCall = DoNotCall;
            if(zip != oldZip){
                if(zip.trim().length() >0){
                    zipcodes = [SELECT id,Name,Region__c,Zip_Code__c FROM Region_ZipCode__c WHERE Zip_Code__c =: zip];
                    if(zipcodes != null && zipcodes.size() > 0){
                        if(zipcodes[0].Region__c != null){
                            Region__c region = regionsMap.get(zipcodes[0].Region__c);
                            if(region != null){
                                con.Alumni_Region__c = region.Id;
                                alumniregionView = zipcodes[0].Region__c;
                            }
                        }else{
                            con.Alumni_Region__c = null;
                            alumniregionView = '';
                        }
                    }
                }
             
            }
            con.MailingCountry = country;
            con.Ethnicity__c = race;
            con.Profession__c = profession;
            con.Gender__c = gender;
            con.Policy_Interest__c = pinterest;
            con.Advocacy_Interest__c = ainterest;
            con.Organizing_Interest__c = ointerest;
            con.Corp_Region__c = corpregion;
            con.Employee_Title__c = title;
            con.Employment_Organization__c = employer;
            for(SelectOption so:corpRegions){
                if(so.getValue() == corpregion){
                    corpregionView = so.getLabel();
                }
            }
            /*con.Alumni_Region__c = alumniregion;
            for(SelectOption so:corpRegions){
                if(so.getValue() == alumniregion){
                    alumniregionView = so.getLabel();
                }
            }*/
            con.Corps_Year__c = corpYear;
            if(memberoptout == true){
                con.Member_Stage__c = 'Deactivated';
            }else{
                con.Member_Stage__c = 'Activate';
            }
            String str;
            if(leadership != null){
                System.Debug('@@@@@@@@@@@@Index of [ is'+leadership.indexOf('['));
                if(leadership.indexOf('[') != -1){
                    str = leadership.substring(1,leadership.length()-1);
                }else{
                    str = leadership;
                }
            }
            con.Registered_to_Vote__c = registered;                
            //List<String>pleadership = con.Public_Leadership_Aspirations__c.split(';');
            str = str.replaceAll(',',';');
            System.Debug('@@@@@@@@Value'+str);
            List<String>pleadership = str.split(';');
            System.Debug('@@@@@@@@Size'+pleadership.size());
            con.Public_Leadership_Aspirations__c = str;
            leadership = str;
            /*if(pleadership.size() >= 2 ){             
                
            }else{
                 //ApexPages.addMessage(new ApexPages.message(ApexPages.severity.ERROR, 'Select at least 2 Public Leadership Aspiration'));
                 showErr = true;
                 return;
            }*/
            if(volunteerInterest != null){
                System.Debug('@@@@@@@@@@@@Index of [ is'+volunteerInterest.indexOf('['));
                if(volunteerInterest.indexOf('[') != -1){
                    str = volunteerInterest.substring(1,volunteerInterest.length()-1);
                }else{
                    str = volunteerInterest;
                }
                str = str.replaceAll(',',';');
                con.Volunteer_Interests__c = str;
                volunteerInterest = str;
            }else{
                con.Volunteer_Interests__c = '';
            }
            
            if(imageName != null && imageBody != null){
                filesize = imageBody.size();
                filesize = filesize /(1024*1024);
                if(filesize <= 1){
                    if(con != null && con.id != null){
                        if( contactImage != null && contactImage.Contact__c != null){
                            img = new Attachment(Name = imageName,Body=imageBody,ParentId = contactImage.id);
                            insert img;
                        }else{
                            contactImage = new  Contact_Picture__c(Contact__c = con.Id);
                            insert contactImage;
                            img = new Attachment(Name = imageName,Body=imageBody,ParentId = contactImage.id);
                            insert img;
                        }
                        imagesrc = '/servlet/servlet.FileDownload?file='+img.id;
                        imageBody = null;
                        img = null;
                    }
                    isError = false;
                }else{
                    imageBody = null;
                    img = null;
                    isError = true;
                    errorMsg = 'File Size can not be more than 1 MB';
                    return null;
                    //ApexPages.addMessage(new ApexPages.message(ApexPages.severity.ERROR, 'File Size can not be more than 1 MB'));
                }
                upsert con;
                isEditable = false;
                showErr = false;
                System.debug('@@@@ Values are '+con.Policy_Interest__c+'==='+ con.Advocacy_Interest__c + '==='+con.Organizing_Interest__c);
            }
        }catch(Exception ex){
            //ApexPages.addMessage(new ApexPages.message(ApexPages.severity.ERROR, ex.getMessage()));
            isError = true;
            errorMsg = ex.getMessage();
            return null;
        }
        upsert con;
        isEditable = false;
        showErr = false;
        return new PageReference('/MyProfile');
    }
    public void edit(){
        isEditable = true;
    }
    
    public PageReference cancel(){
        isEditable = false;
        if(con != null){
                fname = con.FirstName;
                lname = con.LastName;
                fullmiddelName = con.Full_Middle_Name__c;
                home = con.HomePhone;
                mobile = con.MobilePhone;
                work = con.Phone;
                pemail = con.Email;
                semail = con.Secondary_Email__c;
                facebook = con.Facebook__c;
                twitter = con.Twitter__c;
                linkedin = con.Linked_In__c;
                street = con.MailingStreet;
                city = con.MailingCity;
                state = con.MailingState;
                zip = con.MailingPostalCode;
                country = con.MailingCountry;
                race = con.Ethnicity__c;
                profession = con.Profession__c;
                gender = con.Gender__c;
                pinterest = con.Policy_Interest__c;
                ainterest = con.Advocacy_Interest__c;
                ointerest = con.Organizing_Interest__c;
                corpregion = con.Corp_Region__c;
                alumniregion = con.Alumni_Region__c;
                corpYear = con.Corps_Year__c;
                title = con.Employee_Title__c;
                employer = con.Employment_Organization__c;
                if(con.Member_Stage__c == 'Deactivated'){
                    memberoptout = true;
                }else{
                    memberoptout = false;
                }
                showErr = false;
        }
        return new PageReference('/MyProfile');
    }  
Daniel GageDaniel Gage
  
@istest    
    
   
public static  void MyProfileTest1(){
        
         String fname;
           String lname;
        string contactid;
        contactId = '003M000000Dp9z9';
        System.assertEquals(fname, 'Daniel');
         System.assertEquals(lname, 'Gage');
        Region__c region = new Region__c(Name = 'Memphis');
        insert region;
        
        Contact con = new Contact();
        
        con.LastName = 'Testing';
        con.FirstName = 'test1';
        con.Twitter__c ='http://www.twitter.com';
        con.Secondary_Email__c = 'test1@gmail.com';
        con.Ethnicity__c ='African-American';
        con.Profession__c = 'Law/Legal Services';
        con.Policy_Interest__c = 'Interest now';
        con.Phone ='565565656';
        con.Organizing_Interest__c = 'Interest now';
        con.MobilePhone ='9887935716';
        con.Member_Stage__c ='Interested';
        con.Linked_In__c ='http://in.linkedin.com/';
        con.LeadSource ='Website';
        con.HomePhone ='5762572';
        con.Gender__c ='Male';
        con.Full_Middle_Name__c='test';
        con.Fax ='5683268';
        con.Facebook__c ='http://www.facebook.com';
        con.Email = 'newuser@testorg.com';
        con.Corps_Year__c =String.ValueOf(system.today().year());
        con.Corp_Region__c = region.Id;
        con.Birthdate = system.today();
        con.Alumni_Region__c = region.Id;
        con.Advocacy_Interest__c ='Interest now';
        con.MailingPostalCode = '32093';
        insert con;
        con.MailingPostalCode ='302020';
        update con;
        
        Contact_Picture__c conPicture= new Contact_Picture__c();
        conPicture.Contact__c = con.id;
        insert conPicture;
        
        Region_ZipCode__c rZip = new Region_ZipCode__c(Region__c='Memphis',Zip_Code__c='30202');       
        insert rZip;
        
        Profile p = [SELECT Id FROM Profile WHERE Name='Overage Authenticated Website User'];
        User u1 = new User(Alias = 'newUser', Email='newuser@testorg.com',
                            EmailEncodingKey='UTF-8', LastName='Testing', LanguageLocaleKey='en_US',
                            LocaleSidKey='en_US', ProfileId = p.Id,
                            TimeZoneSidKey='America/Los_Angeles', UserName='newuser@testorg.com',contactId=con.Id);
        
        System.runAs(u1){
            System.debug('Current User: ' + UserInfo.getUserId());
            System.debug('Current Profile: ' + UserInfo.getProfileId());                           
        
            Attachment attachment = new Attachment(Name='An attachment',body=blob.valueof('b'),parentId=con.Id);
            try{
                insert attachment;
            }         
            catch(exception e)
            {}             
            //ApexPages.currentPage().getParameters().put('contactId',con.Id);
            
            MyProfileController mpc = new MyProfileController();
            mpc.zip ='30202';            
            mpc.imageName ='An attachment';
            mpc.imageBody =blob.valueof('b');
            mpc.upload();
            mpc.leadership ='Interested in Learning More';
            mpc.volunteerInterest = 'Letter writing to news media';
            mpc.imageName ='An attachment';
            mpc.imageBody =blob.valueof('b');
            mpc.save();
            mpc.edit();
            mpc.cancel();
        }
    }
 
Daniel GageDaniel Gage

I know this is a long one. But it's why I can't seem to figure out how I can get any coverage on it. (in the live system it is at 0 percent, and according to SF Support this is the one that is causing all my grief. I just need to get a test class for it that will bring it to 1 percent and they say I should be fine.

I can't figure out how to get the First part (with all the set, get's) to get any coverage at all.

Thank you in advance. This site has been absolutely invaluable to me.

Roy LuoRoy Luo
System.runAs(user){
    PageReference p = Page.YourVfPage;
    Test.setCurrentPage(p); 
    MyProfileController ctrl = new MyProfileController();
    ctrl.edit();
    ctrl.cancel();
    ctrl.save();
    
}
PS. see https://developer.salesforce.com/forums/ForumsMain?id=906F0000000Aoss
This was selected as the best answer
Daniel GageDaniel Gage

Roy Thank you again.
 

Whomever they had developing before was really bad at actually generating test classes. I'm not sure how he/she/they were able to push these into production in the shape they are in.

 

Roy LuoRoy Luo
Frankly you would be better off rewriting the whole thing. Most of the propety get/set can go away, just have one
public Contact ContactObj {get;set;} and use ContactObj to bind to the UI elements. I just could not believe those codes or developers were out there. 
Daniel GageDaniel Gage
thats not necc a bad idea.  Thanks again for your help. Sent from Yahoo Mail on Android