You need to sign in to do that
Don't have an account?

How do add test code for email class.
Could someone help me write the test code for the below class. I am new at this and don't have a clue on how to write the code for emailing and batch process. What I have so far is below. global class OpportunityNotices implements Database.Batchable<sObject>,Database.Stateful { Map<Id , List<Opportunity>> userOppMap {get; set;} List<Opportunity> allOppNotices {get; set;} global OpportunityNotices() { Date CalDate = date.Today().addDays(10); //Map to maintain user id and cases logged by them today userOppMap = new Map<Id, List<Opportunity>>() ; //All sales rep (System admins) List<User> salesRep = new List<User>() ; salesRep = [select id , name , Email from User where isactive = true] ; //All sales rep ids List<Id> salesIds = new List<Id>() ; for(User ur : salesRep) { salesIds.add(ur.Id) ; } //find a list of Opportuntities with overdue est decision dates allOppNotices = new List<Opportunity>(); allOppNotices = [SELECT Id, StageName, CloseDate, name, OwnerID FROM Opportunity WHERE CloseDate <= : CalDate AND StageName != 'Closed Won' AND StageName != 'Closed Lost' Order By OwnerID, ID ]; } global Database.QueryLocator start(Database.BatchableContext BC) { //Creating map of user id with opportunities that are due or overdue for(opportunity c : allOppNotices) { if(userOppMap.containsKey(c.ownerId)) { //Fetch the list of case and add the new case in it List<Opportunity> tempList = userOppMap.get(c.ownerId) ; tempList.add(c); //Putting the refreshed case list in map userOppMap.put(c.ownerId , tempList) ; } else { //Creating a list of case and outting it in map userOppMap.put(c.ownerId , new List<Opportunity>{c}) ; } } //Batch on all system admins (sales rep) String query = 'select id , name , Email from User where isactive = true'; return Database.getQueryLocator(query); } global void execute(Database.BatchableContext BC, List<sObject> scope) { for(Sobject s : scope) { //Type cast sObject in user object User ur = (User)s ; //If system admin has logged any case today then only mail will be sent if(userOppMap.containsKey(ur.Id)) { //Fetching all cases logged by sys admin List<Opportunity> allOppOfSalesRep = userOppMap.get(ur.Id) ; String body = '' ; //Creating tabular format for the case details body = BodyFormat(allOppOfSalesRep) ; //Sending Mail Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage() ; //Setting user email in to address String[] toAddresses = new String[] {ur.Email} ; // Assign the addresses for the To and CC lists to the mail object mail.setToAddresses(toAddresses) ; //String[] ccAddresses = new String[] {'ekfree@wctc.net'}; //mail.setccaddresses(ccaddresses); mail.setreplyto('_DL_NP_SFDC_ADMIN@newpagecorp.com'); //Email subject to be changed mail.setSubject('Opportunity Due Notice'); //Body of email mail.setHtmlBody('Please review and update the opportunities listed below by updating the estimated decision date or closing the opportunity if it is no longer active. ' + '<br/> <br/> ' + body + '<br/> ' + 'Thank you.'); //Sending the email Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail }); } } } public String BodyFormat(List<Opportunity> opps) { String str = '' ; for(Opportunity cs : opps) { Date dt = cs.closedate; String dateStr = DateTime.newInstance(dt.year(),dt.month(),dt.day()).format('MM/dd/yyyy'); str += '<tr><td colspan="2">'+ cs.Name +'</td>'+'<td colspan="2">'+ dateStr +'</td>'+'<td>'+ '</td>'+'<td>'+ '</td>'+'</tr>' ; } str = str.replace('null' , '') ; String finalStr = '' ; finalStr = '<table border=" "> <td colspan="2">Name </td> <td colspan="2">Est. Decision Date </td> '+'<td>'+ '</td>'+'<td>'+ '</td>'+ str +'</table>' ; return finalStr ; } global void finish(Database.BatchableContext BC) { AsyncApexJob a = [Select id, status, numberoferrors, jobitemsprocessed, totaljobitems, createdby.email from AsyncApexJob where id = :BC.getjobid()]; //send email Messaging.singleemailmessage mail = new messaging.singleemailmessage(); string[] toadd = new string[] {'karol.freeberg@newpagecorp.com'}; mail.settoaddresses(toadd); mail.setsubject('Opportunity Notices Job Completed ' + a.status); mail.setplaintextbody ('The batch apex job processed ' + a.totaljobitems + ' batches with ' + a.numberoferrors + ' failures.'); messaging.sendemail (new messaging.singleemailmessage[] {mail}); } }
@isTest class OpportunityNoticesTest { Static testmethod void test() { //query used by the batch job String query = 'select id , name , Email from User where isactive = true'; //Test data Opportunity[] op = new List<opportunity>(); For (integer i=0; i < 5;i++) { Opportunity o = new opportunity( Closedate = date.Today().addDays(-16), StageName = 'Target', Name = '2014-AARP' + i, reason_won_lost__C = 'Freight;History', annual_volume__c = 3, type = 'New Business', tons_won__c = 15, frequency__c = 'Spot', End_Use__c = 'This is the end use', start_Date__c = date.today()); op.add(o); } //End for loop Test.starttest(); Integer batchSize = 1; OpportunityNotices OppN = new OpportunityNotices(); if(!Test.isRunningTest()){ Database.executeBatch(OppN, batchSize); } Test.StopTest(); } //End testmethod } //End
All Answers
I think you are going in the right direction, but I am not sure why you have !Test.isRunningTest() on line 30. ?? Please remove that line and run your test class.
For the Email, it would execute the lines of code and simulate sending email, you can if you want to capture result, please use sendEmailResult.
https://www.salesforce.com/us/developer/docs/api/Content/sforce_api_calls_sendemail_emailresult.htm
Hope this helps
Looking more into your actual batch class, I am not sure why few things are done the way they are done. I made some changes to move code around, can you please try using the below and see if it works.
Your test class would be
PS: I have not added asserts, Please make sure that you add asserts to test classes wherever needed
o.OwnerId = UserInfo.getUserId();
system.assertEquals(o.OwnerId,UserInfo.getUserId());
or
List<Opportunity> newlyInserted = [Select Id, Name from Opportunity where OwnerId = :UserInfo.getUserId()];
system.assertEquals(5,newlyInserted.size());
Thank you so much for your help!!!!! You managed to turn a fustrating situation into something of value. Thanks again!