3

I was wondering if there is a way to make a Test class only run for the Apex Class it's made for. Every time I want to import new classes or triggers, I have to turn off all of my scheduled Apex, then do the import, then remember to re-schedule it all. Here is an example of one that just sends an email

Class:

global class ClientCare_FundUpdate_MonthlyEmail implements Database.Batchable<sObject>{
global Database.QueryLocator start(Database.BatchableContext BC){
    /* Criteria for Batch job
    Email  != null
    RecordTypeId = '012d0000000t7JQ'
    Status__c = 'Active'
    Stage__c != 'Candidate'
    Program__c = 'Open Doors', 'Canine Magic'
    Remaining_Balance__c > 0.00
    Total_Expected_Funds__c > 0.00
    All_Funds_Received_Email__c = NULL
    Candidate_Stage_Date__c != NULL
    */
   return Database.getQueryLocator([select Owner.Email,OwnerId,CC_Emails_To__c,id,Name,Candidate_Stage_Date__c from contact where email != null and  RecordTypeId = '012d0000000t7JQ' and Status__c = 'Active' and Stage__c = 'Candidate' and Program__c in ('Open Doors','Canine Magic') and Remaining_Balance__c > 0.00 and Total_Expected_Funds__c > 0.00 and All_Funds_Received_Email__c = NULL and Candidate_Stage_Date__c != NULL ]);
}
global void execute(Database.BatchableContext BC, List<sObject> scope){
      BatchJob(scope);      
}
global void finish(Database.BatchableContext BC){
}  
public STATIC void  BatchJob(List<sObject> scope)
{
    List<Messaging.SingleEmailMessage> mailList = new List<Messaging.SingleEmailMessage>();        
    for(sobject s : scope){
        contact Con = ((contact)S);           
        if(system.today()>Con.Candidate_Stage_Date__c.adddays(15))
        {
                OrgWideEmailAddress[] owea = [select Id from OrgWideEmailAddress where Address = :con.Owner.Email limit 1];
                String oweaId = '0D2d0000000TOOZ';
                if(owea.size()>0){
                    oweaId = owea.get(0).Id;
                }                    
                String TemplateId = '00Xd0000000k3LY';                    
                List<string> message  =  new List<string>();
                if(Con.CC_Emails_To__c != NULL){                        
                    for(String em :  Con.CC_Emails_To__c.split(';',0) )
                    {
                        if(validateEmail(em))
                        {
                            message.add(em);
                        }   
                    }                        
                }              
                mailList.add(CreateEmail(con ,TemplateId  ,oweaId,message)) ;
        }   
    }
     if(mailList.size() > 0)
     {
         Messaging.sendEmail(mailList,true);
     }
}
public static Boolean validateEmail(String email) {
    Boolean res = true;               
    String emailRegex = '^[a-zA-Z0-9._|\\\\%#~`=?&/$^*!}{+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,4}$'; // source: http://www.regular-expressions.info/email.html
    Pattern MyPattern = Pattern.compile(emailRegex);
    Matcher MyMatcher = MyPattern.matcher(email);    
    if (!MyMatcher.matches()) 
    {
        res = false;
    }
    return res; 
}
Public Static  Messaging.SingleEmailMessage CreateEmail(Contact c ,String TemplateId ,String OrgwideEmailId,List<string> message  )
{
   Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
   mail.setTemplateId(TemplateId ); 
   mail.setOrgWideEmailAddressId(OrgwideEmailId);
   mail.setTargetObjectId(c.id);
   if(message != null && message.size() > 0 )
   {
        mail.setCcAddresses(message);            
   }   
   return mail;   
 }
}

Schedulable Class:

global class ClientCare_FundUpdate_MonthlySch implements Schedulable{


   global void execute(SchedulableContext SC) {
                 ClientCare_FundUpdate_MonthlyEmail   CCBatch = new ClientCare_FundUpdate_MonthlyEmail (); 
                 database.executebatch(CCBatch,100);
   }

   /**    
    ClientCare_FundUpdate_MonthlySch m = new  ClientCare_FundUpdate_MonthlySch();
    String sch = '0 0 5 1 * ? * ' ;
    system.schedule('ClientCare_FundUpdate_MonthlySch', sch, m);
    */
}

Test Class:

@isTest
public class ClientCare_FundUpdate_Monthly_Test{
    private static testmethod void test_ClientCare_FundUpdate_Monthly(){

        User u = [select id from user where profile.name like '%Client Care%' and isactive = true limit 1 ];

        System.RunAs(u){   
            Account a = new Account(
                Name = 'Testclass'                
            );

            Contact c = new Contact(
                LastName = 'Testclass', 
                RecordTypeId = '012d0000000t7JQ',
                Status__c = 'Active',
                Stage__c = 'Candidate',
                Program__c = 'Open Doors',
                Email = '[email protected]',
                CC_Emails_To__c = '[email protected];',
                Candidate_Stage_Date__c= system.today().addDays(-25)
            );
            insert c;

            Campaign cp = new Campaign(
                Name = 'Testclass',
                Status = 'In Progress',
                RecordTypeId = '012d0000000SvFG',
                Client__c = c.id,
                ExpectedRevenue = 8500.00
            );
            insert cp;

            Application__c app = new Application__c(
                Name__c = c.id,
                Client_Campaign__c = cp.id
            );
            insert app;

            c.Current_Application__c = app.id;
            update c;

            Opportunity o = new Opportunity(
                Name = 'Test_TT', 
                AccountId = a.id,
                CloseDate = System.today(),
                StageName='Posted',
                cp_Transaction_Type__c = 'Team Training Deposit',
                CampaignId = cp.id,
                Amount = 8000.00,
                Deposit__c = TRUE
            );
            insert o;

            Contact chkC = [select id from Contact where id=:c.id];            


        Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage(); //create new email variable
        mail.setTemplateId('00Xd0000000k3LY');    //set Email template id for this email
        mail.setReplyTo('005d0000001knHV');  //Org wide email for sender address it must need to be verified.
        mail.setTargetObjectId(chkC.id);   ///setting contact id as who id.            

            Test.startTest();
                    ClientCare_FundUpdate_MonthlyEmail   CCBatch = new ClientCare_FundUpdate_MonthlyEmail(); 
                    database.executebatch(CCBatch,100);
            Test.stopTest();      


            System.assertEquals(1,[Select Id from Task where Subject = 'Email: Candidate Funding Status'].size());


        }
    }
    public static testmethod void DailySchEmailJobtest() {

       Test.startTest();
       String sch = '0 0 5 ? * * * ' ;
       String jobId = System.schedule('ClientCare_FundUpdate_MonthlySch',sch ,          new ClientCare_FundUpdate_MonthlySch());
       Test.stopTest();
   }        
}
3
  • 1
    When you are deploying your new code, are you also deploying the scheduled class? Mar 19, 2014 at 16:29
  • No. But since they are all already scheduled on Production, when I try to deploy new code, it tries to run the test class for the scheduled class at the same time and I get an error saying that it can't because they are already scheduled for execution.
    – Jennifer
    Mar 19, 2014 at 17:09
  • When there is a huge number of classes this will be a pain, but you can create a User as you currently doing and run whatever you need to test by that particular user. In the class or trigger, check whether it's firing from a test class or not. If it's from a test class, then check whether it's running by that particular user.
    – highfive
    Mar 19, 2014 at 18:19

1 Answer 1

4

I think you can just modify your test to schedule the class with a different name.

public static testmethod void DailySchEmailJobtest() {
       Test.startTest();
       String sch = '0 0 5 ? * * * ' ;
       String jobId = System.schedule('ClientCare_FundUpdate_MonthlySchTest', sch, new ClientCare_FundUpdate_MonthlySch());
       Test.stopTest();
}
1
  • 1
    Great! Thank you so much! Wish I would have asked this 2 months ago :)
    – Jennifer
    Mar 19, 2014 at 20:38

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .