Take the 2-minute tour ×
Salesforce Stack Exchange is a question and answer site for Salesforce administrators, implementation experts, developers and anybody in-between. It's 100% free, no registration required.

I have created the following Apex class below, however i have 0% code coverage

Apex Class Name : DeactivateUsers

global class DeactivateUsers implements Schedulable
{

    Public static void SendLoginEmail(String bucket, String[] adminemail, List<User> ulist){


    String timeleft = '';

    if(bucket == '1'){
        timeleft = ' 30 days ';
    }
    else{
        timeleft = ' 7 days ';
    }

    List<Messaging.SingleEmailMessage> theEmails = new List<Messaging.SingleEmailMessage>();    

    for(Integer i=0;i<ulist.size();i++){
        Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
        mail.setUseSignature(false);
        mail.setSenderDisplayName('Global CRM Team');
        mail.setTargetObjectId(ulist[i].Id);
        mail.saveAsActivity = false;
        mail.setCcAddresses(adminemail);
        mail.setSubject('Your Salesforce account is scheduled for de-activation');
        mail.setHtmlBody('<p>Dear ' + ulist[i].Name + ',</p><p> You have ' + timeleft + 'to login to your Salesforce account.  If you do not login within the next' + timeleft + 'your account will be deactivated. </p><p> Regards,</p> <p>Global CRM Team</p>');

        theEmails.add(mail);
    }

    if(theEmails.size()>0){ 

        Messaging.SendEmailResult[] results = Messaging.sendEmail( theEmails );

    }

    }



    global void execute(SchedulableContext ctx)
    {
        // to run the job only in production.  Amended by Daniel Mason on 22/04/2014
            if (UserInfo.getOrganizationId() == '00D20000000mJwIEAU') {
            system.debug('*****orgid*****'+UserInfo.getOrganizationId());
            Date myDate = Date.Today();
            String sDate = String.valueOf(myDate);

            //describe the User_Region__c field to get the picklist values
            Schema.DescribeFieldResult fieldResult = User.User_Region__c.getDescribe();

            //put the describe results into a list
            List<Schema.PicklistEntry> ple = fieldResult.getPicklistValues();

            //create a list to hold the regions that you want to include in the query
            List<String> myregions = new List<String>();

            //this is where you add the values to your myregions list
            for (Schema.PicklistEntry a : ple ) {
                    if(a.getValue().contains('Asia') || a.getValue().contains('Japan')){
                    //do not add to search list
                }
                else{
                    //add to the search list
                    myregions.add(a.getValue());
                }
            }

            //hold the users to deactivate
            List<User> updUsers = new List<User>(); 
            String Usr = '';
            String Usr1 = '';
            String Usr2 = '';

            String[] AdminEmail = new String[]{};
            AdminEmail.add('daniel.Mason@domain .com');


            String[] DeveloperEmail = new String[]{};
            DeveloperEmail.add('daniel.Mason@domain .com');

            String eMailSub = '';
            String eMailbdy = '';


            List<User> UserList = new List<User>(); 

            //hold the users at 90 days

            List<User> Bucket1 = new List<User>();

            //hold the users at 113 days

            List<User> Bucket2 = new List<User>();

            if(Test.isRunningTest()) 
            {
                // To increase the code coverage during running the test class
                UserList = [
                SELECT Id, Name,isactive,lastlogindate,createddate,Inactive_Date__c
                FROM User
                WHERE 
                isactive = False and Inactive_Date__c= null
                LIMIT 2];
            }
            else
            {


                UserList = [ SELECT Id, Name,isactive,lastlogindate,createddate, Inactive_Date__c
                FROM User
                WHERE isactive = True
                AND User_Region__c =: myregions
                AND Management_User__c = False
                AND Management_User__c = false
                AND Eloqua_User__c = false
                AND Function__c = null
                and Local_Administrator__c Not In ('IT Support, System or Integration','Training or Test')
                ];

            }


            Integer i =1;
            Integer j =1;
            Integer k =1;

            for(user u: UserList)
                {
                integer Days;

                if(u.lastlogindate == null){
                    Days = Integer.valueOf((System.Now().getTime() - u.CreatedDate.getTime())/(1000*60*60*24));
                }else{
                    Days = Integer.valueOf((System.Now().getTime() - u.lastlogindate.getTime())/(1000*60*60*24));
                } 
                if(Test.isRunningTest()){
                if(Days == 0){
                    Usr1 = Usr1 + j+'. '+u.name +  '<br/>';
                    j = j+1; 
                    Bucket1.add(u);

                    Usr2 = Usr2 + k+'. '+u.name +  '<br/>';
                    k = k+1; 
                    Bucket2.add(u);

                    Usr = Usr + i+'. '+u.name +  '<br/>';
                    i = i+1; 
                    u.isActive = False;
                    u.Inactive_Date__c = System.Today();
                    updUsers.add(u);

                }
                }
                else{

                    if(Days == 90){
                        Usr1 = Usr1 + j+'. '+u.name +  '<br/>';
                        j = j+1; 
                        Bucket1.add(u);
                    }
                    else if(Days == 113){
                        Usr2 = Usr2 + k+'. '+u.name +  '<br/>';
                        k = k+1; 
                        Bucket2.add(u);
                    }
                    else if(Days >=120){
                        Usr = Usr + i+'. '+u.name +  '<br/>';
                        i = i+1; 
                        u.isActive = False;
                        u.Inactive_Date__c = System.Today();
                        updUsers.add(u);
                    } 
                    else{
                        //do nothing
                    } 
                }
            }

            //process the 30 days to deactivation  emails
            if(Bucket1.size()>0)
            {
            try
            {
                SendLoginEmail('1',AdminEmail, Bucket1); 

                sndEmail(AdminEmail,'30 Day notice sent List for '+sDate,'Dear Administrator,<br/><br/>The following domain users have been sent the 30 day deactivation notice during todayís run.<br/><br/>'+Usr1);
            }
            catch(Exception e)
            {
                system.debug('Exception:'+e);
                sndEmail(AdminEmail,'Exception in 30 Day notice emails '+sDate,'Dear Administrator,<br/><br/><font color="red">The following exception has stopped todays 30 day deactivation notice during todayís Run.<br/><br/>'+e+'<br/><br/></font> The below users will have to be manually emailed.<br/><br/>'+Usr1);
            }
            }
            else
            {
                sndEmail(DeveloperEmail,'No 30 day notice emails  '+sDate,'Dear Administrator,<br/><br/>There are no 30 day notices sent today');
            }

            //process the 1 week to deactivation  emails
            if(Bucket2.size()>0)
            {
                try
                {
                    SendLoginEmail('2', AdminEmail,Bucket2);  

                    sndEmail(AdminEmail,'1 week notice sent List for '+sDate,'Dear Administrator,<br/><br/>The following domain users have been sent the 1 week deactivation notice during todayís run.<br/><br/>'+Usr2);
                }
                catch(Exception e)
                {
                    system.debug('Exception:'+e);
                    sndEmail(AdminEmail,'Exception in 1 week notice emails '+sDate,'Dear Administrator,<br/><br/><font color="red">The following exception has stopped todays 1 week deactivation notice during todayís Run.<br/><br/>'+e+'<br/><br/></font> The below users will have to be manually emailed.<br/><br/>'+Usr2);
                }
            }
            else
            {
                sndEmail(DeveloperEmail,'No 1 week notice emails  '+sDate,'Dear Administrator,<br/><br/>There are no 1 week notices sent today');
            }

            //process the user deactivation
            if(updUsers.size()>0)
            {
                try
                {
                    system.debug('Try Part  --- UpdUsersListSize--'+updUsers.size());   
                    update updUsers;
                    system.debug('Try Part after update');   
                    sndEmail(AdminEmail,'Deactivated User List for '+sDate,'Dear Administrator,<br/><br/>The following domain users have been deactivated during todayís run.<br/><br/>'+Usr);
                }
                catch(Exception e)
                {
                    system.debug('Exception:'+e);
                    sndEmail(AdminEmail,'Exception in Deactivate Users '+sDate,'Dear Administrator,<br/><br/><font color="red">The following exception has stopped todays Deactivate Users Run.<br/><br/>'+e+'<br/><br/></font> The below users will have to be manually deactivated.<br/><br/>'+Usr);
                }
            }
            else
            {
                sndEmail(DeveloperEmail,'No Deactivated Users '+sDate,'Dear Administrator,<br/><br/>There are no deactived users today');
            }



        }
    }

    Public void sndEmail(String[] ToAdr,String Sub, String bdy){
    Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
    mail.setUseSignature(false);
    mail.setSenderDisplayName('Global CRM Team');
    mail.setToAddresses(ToAdr);
    mail.setSubject(Sub);
    mail.setHtmlBody(bdy);
    Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
    }
}

This is my test class Apex Class Name : DeactivateUsers_Test

@istest
private class DeactivateUsers_Test {
    static testMethod void testuserdeactivate() {
        String mydomain = 'domain.com';
        List tobeadded = new List();

        //enter the profile name below that you want to set for the test users.
        Profile prof = [select id from profile where name='NL: Sales & Marketing User'];

        //make sure to add/remove the fields below that are required at your company to create new users
        //create test user 3
        User u3 = new User();
        u3.email = 'u3user@' + mydomain;
        u3.lastname = 'tester';
        u3.firstname = 'u3user';
        u3.emailencodingkey='UTF-8';
        u3.alias = 'u3user';
        u3.languagelocalekey='en_US';
        u3.localesidkey='en_US';
        u3.timezonesidkey='America/Los_Angeles';
        u3.profileid = prof.Id;
        u3.isactive = False;
        u3.Inactive_Date__c = null;
        u3.username='u3user@' + mydomain;

        //add test user to the tobeupdated list
        tobeadded.add(u3);

        //create user 4
        User u4 = new User();
        u4.email = 'u4user@' + mydomain;
        u4.lastname = 'tester';
        u4.firstname = 'u4user';
        u4.emailencodingkey='UTF-8';
        u4.alias = 'u4user';
        u4.languagelocalekey='en_US';
        u4.localesidkey='en_US';
        u4.timezonesidkey='America/Los_Angeles';
        u4.profileid = prof.Id;
        u4.isactive = False;
        u4.Inactive_Date__c = null;
        u4.username='u4user@' + mydomain;

        //add test user to the tobeupdated list
        tobeadded.add(u4);

        //insert the list of new users
        insert tobeadded;

        //verify the users were inserted
        List insertedlist = [select Id,Email,isactive from User Where CreatedDate = Today];
        System.debug('list includes: ' + insertedlist);
        System.assertNotEquals(insertedlist,null);

        //test the class again since the users should have been updated and will not match the query this time. DeactivateUsers sh2 = new DeactivateUsers(); String sch2 = '0 0 23 * * ?'; system.schedule('Test DeactivateUsers data', sch2, sh2);
    }
}
share|improve this question
    
@ Simon Lawrence, I apologise for the vast amounts of code. –  user8746 Jun 17 at 15:43
    
Where in the test are you deactivating the users? I only see users being added. –  Jagular Jun 17 at 15:59
    
@jagular- I have no idea any more, this is confusing me. I hate writing test classes takes me longer to write it than the actually class. –  Masond3 Jun 17 at 16:49
2  
I looked closer. It appears that your class is meant to run on a schedule and deactivate the users that meet the criteria. Richard N has the answer; your test class should use system.schedule. BTW, it's not at all unusual for test classes to take significant time to write. –  Jagular Jun 17 at 19:06

2 Answers 2

up vote 1 down vote accepted

Your class gets no coverage because the line that actually calls your scheduled class is commented out in your test:

//test the class again since the users should have been updated and will not match the query this time. DeactivateUsers sh2 = new DeactivateUsers(); String sch2 = '0 0 23 * * ?'; system.schedule('Test DeactivateUsers data', sch2, sh2);

Split this into and add the test declarations:

//test the class again since the users should have been updated and will not match the query this time.
Test.startTest();
DeactivateUsers sh2 = new DeactivateUsers();
String sch2 = '0 0 23 * * ?';
System.schedule('Test DeactivateUsers data', sch2, sh2);
Test.stopTest();
share|improve this answer
    
hi dphil - Test class has now passed. however my Code Coverage 44% (48/108). where am i going wrong ? –  user8746 Jun 18 at 8:02
    
A lot of your criteria is going to be near impossible to hit. You have some try/catch statements that won't ever be getting hit. I noticed that the criteria for one catch statement is for an email to fail which in turns sends another email. I don't think you need to have that sort of check and you will never hit the catch. This might be worth another question though since your original question just asked about why you have 0% coverage and that's what everyone else will likely be looking for. –  dphil Jun 18 at 13:47

Your class implements the Schedulable interface. This is done asynchonously so you need your class to execute before testing aginst it.

Please read the test section here and you will need to modify your test class method accordingly.

http://www.salesforce.com/us/developer/docs/apexcode/Content/apex_scheduler.htm

You will need to use System.Schedule in your test method just like how you would schedule your class in the developer console. It should be between the Test.StartTest() and Test.Stoptest()

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.