0

I tried to get the coverage inside the for..

this is the code : enter image description here

and this is my test class :

Profile profileId = [SELECT Id FROM Profile WHERE Name = 'Manager CS' LIMIT 1];
    User usr = new User(LastName = 'LIVESTON',
                       FirstName='JASON',
                       Alias = 'jliv',
                       Email = '[email protected]',
                       Username = '[email protected]',
                       ProfileId = profileId.id,
                       TimeZoneSidKey = 'GMT',
                       LanguageLocaleKey = 'en_US',
                       EmailEncodingKey = 'UTF-8',
                       LocaleSidKey = 'en_US'
                       );

    Named_User__c nu = new Named_User__c();
        nu.User__c = usr.id;    
        nu.name = 'test';
        nu.First_Name__c = 'test';
        nu.Email__c = '[email protected]';
        nu.First_Name__c = 'test';
        insert nu;  

I tried to see the result of my query and it return so many records.. so there`s no issue with the query.. and I cant figure it why my test class not cover the inside of this for..

this is my full code :

global class SendedEmail implements Schedulable  {

public static String CRON_EXP = '0 0 7 * * ? *';
global void execute(SchedulableContext ctx) {

Date now = Date.today();
Integer thisday = now.Day();
Integer thismonth = now.month();
Integer thisyear = now.year();

    List<Messaging.SingleEmailMessage> mails = new List<Messaging.SingleEmailMessage>();
    EmailTemplate et = [SELECT Id, Subject, HtmlValue FROM EmailTemplate WHERE developerName = 'ET_Daily_Birthday_List'];

    String subject = et.Subject;                            
    String htmlBody = et.HtmlValue;

    Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage(); 

    htmlBody += '<table border="1" style="border-collapse: collapse; padding:5px;"><tr><th style="padding:5px;"><b>Nama Perusahaan</b></th><th style="padding:5px;"><b>Tanggal Pendirian</b></th><th style="padding:5px;"><b>VIP by Min Revenue</b></th><th style="padding:5px;"><b>VIP by Rank</b></th><th style="padding:5px;"><b>Total Revenue</b></th><th style="padding:5px;"><b>Email</b></th><th style="padding:5px;"><b>Alamat</b></th></tr>';

    List <Custom_Emaill_Log__c> listCustomer = [SELECT Id,Customer__r.Street__c, Customer__r.Name,Customer__r.VIP_Type_Rangking__c,Customer__r.VIP_Type_Revenue__c, Contact__r.Name, Contact__r.Posisi__c, Tipe_Data__c, Actual_Send_Date__c, Status__c, Send_Date__c, Customer__r.Total_Revenue__c, Email__c, Customer__r.Company_Type__c
                                                FROM Custom_Emaill_Log__c WHERE Status__c = 'Send' AND Tipe_Data__c = 'Customer' AND DAY_ONLY(Actual_Send_Date__c) =:now ORDER BY Customer__r.Total_Revenue__c DESC];

    List <Custom_Emaill_Log__c> listContact = [SELECT Id,Contact__r.Street__c, Customer__r.Name,Customer__r.VIP_Type_Rangking__c,Customer__r.VIP_Type_Revenue__c, Contact__r.Name, Contact__r.Posisi__c, Tipe_Data__c, Actual_Send_Date__c, Status__c, Send_Date__c, Customer__r.Total_Revenue__c, Email__c, Customer__r.Company_Type__c
                                                FROM Custom_Emaill_Log__c WHERE Status__c = 'Send' AND Tipe_Data__c = 'Contact' AND DAY_ONLY(Actual_Send_Date__c) =:now ORDER BY Contact__r.Name ASC];

    for (Custom_Emaill_Log__c cel : listCustomer){

                   String companyName = cel.Customer__r.Name;
                   String birthdate = String.valueof(cel.Send_Date__c);

        String viprevenue;
        if (cel.Customer__r.VIP_Type_Rangking__c != NULL){
            viprevenue = cel.Customer__r.VIP_Type_Rangking__c;    
        }
        else {
            viprevenue = '-';    
        }

        String vipranking;
        if(cel.Customer__r.VIP_Type_Revenue__c != NULL){
            vipranking = cel.Customer__r.VIP_Type_Revenue__c;
        }
        else {
            vipranking = '-';
        }

                   String revenue = String.valueof(cel.Customer__r.Total_Revenue__c);
                   String email = cel.Email__c;
                   String address = cel.Customer__r.Street__c;                           
                   String companyType = cel.Customer__r.Company_Type__c +'.';                                                 

               htmlBody += '<tr><td style="padding:5px;">' + companyType + companyName +'</td><td style="padding:5px;">' + birthdate + '</td><td style="padding:5px;">' + viprevenue + '</td><td style="padding:5px;">' +  vipranking +  '</td><td style="padding:5px;">' + revenue +'</td><td style="padding:5px;">' + email +'</td><td style="padding:5px;">' + address +'</td></tr>';   

        }
               htmlBody += '</table><br><br>Berikut ini adalah list Customer yang hari ini ber-Ulang Tahun : <br><br>';   
               htmlBody += '<table border="1" style="border-collapse: collapse; padding:5px;"><tr><th style="padding:5px;"><b>Nama Pimpinan</b></th><th style="padding:5px;"><b>Nama Perusahaan</b></th><th style="padding:5px;"><b>Jabatan</b></th><th style="padding:5px;"><b>Tanggal Ulang Tahun</b></th><th style="padding:5px;"><b>VIP by Min Revenue</b></th><th style="padding:5px;"><b>VIP by Rank</b></th><th style="padding:5px;"><b>Total Revenue</b></th><th style="padding:5px;"><b>Email</b></th><th style="padding:5px;"><b>Alamat</b></th></tr>';

    for (Custom_Emaill_Log__c celc : listContact){

                   String namaPimpinan = celc.Contact__r.Name;     
                   String companyName = celc.Customer__r.Name;
                   String jabatan = celc.Contact__r.Posisi__c;
                   String birthdate = String.valueof(celc.Send_Date__c);

        String viprevenue;
        if (celc.Customer__r.VIP_Type_Rangking__c != NULL){
            viprevenue = celc.Customer__r.VIP_Type_Rangking__c;    
        }
        else {
            viprevenue = '-';    
        }

        String vipranking;
        if(celc.Customer__r.VIP_Type_Revenue__c != NULL){
            vipranking = celc.Customer__r.VIP_Type_Revenue__c;
        }
        else {
            vipranking = '-';
        }

                   String revenue = String.valueof(celc.Customer__r.Total_Revenue__c);
                   String email = celc.Email__c;
                   String address = celc.Contact__r.Street__c;                           
                   String companyType = celc.Customer__r.Company_Type__c +'.';                                               

               htmlBody += '<tr><td style="padding:5px;">' + namaPimpinan + '</td><td style="padding:5px;">' + companyType + companyName +'</td><td style="padding:5px;">' + jabatan + '</td><td style="padding:5px;">' + birthdate + '</td><td style="padding:5px;">' + viprevenue + '</td><td style="padding:5px;">' +  vipranking +  '</td><td style="padding:5px;">' + revenue +'</td><td style="padding:5px;">' + email +'</td><td style="padding:5px;">' + address +'</td></tr>';   

        }

    List<String> sendTo = new List<String>();
    List<Named_User__c> manager = [SELECT Id, User__c, Email__c, Name FROM Named_User__c
                                   WHERE User__r.Profile.Name LIKE '%Manager%'];

        for (Named_User__c nm : manager) { 
            if (nm.Name != null){
                htmlBody = htmlBody.replace('{!User.Name}', nm.Name);
            }
            else{
                htmlBody = htmlBody.replace('{!User.Name}', '[Name Blank]');
            }
            SendTo.add(nm.Email__c);                             
            }

    List<Named_User__c> staff = [SELECT Id, User__c, Email__c, Name FROM Named_User__c
                                WHERE User__r.Profile.Name LIKE '%Staff%'];

        for (Named_User__c nm2 : staff) {
            if (nm2.Name != null){
                htmlBody = htmlBody.replace('{!User.Name}', nm2.Name);
            }
            else{
                htmlBody = htmlBody.replace('{!User.Name}', '[Name Blank]');
            }
            SendTo.add(nm2.Email__c);                             
            }

    OrgWideEmailAddress owa = [select id, Address, DisplayName from OrgWideEmailAddress WHERE Address = '[email protected]' limit 1];   
    for(string sendToEmail : sendTo){

    if(sendToEmail != null){

    system.debug('===strOwnerEmail===='+sendToEmail);


    //String [] toaddress= New String[]{'[email protected]'};
    mail.setOrgWideEmailAddressId(owa.Id);
    mail.setToAddresses(sendTo);
    mail.setSenderDisplayName('IPC - System Administrator');
    mail.setSubject(subject);
    mail.setHtmlBody(htmlBody);

    //List<String> ccTo = new List<String>();    
    //ccTo.add('[email protected]');
    //mail.setCcAddresses(ccTo);

    mail.setSaveAsActivity(false);
    mails.add(mail);

    }
    }
        Messaging.sendEmail(mails);    
}
}

and the test class :

@isTest
public class SendedEmail_Test {

    static testMethod void myTest() {


        Profile profileId = [SELECT Id FROM Profile WHERE Name = 'Manager CS' LIMIT 1];
        User usr = new User(LastName = 'LIVESTON',
                           FirstName='JASON',
                           Alias = 'jliv',
                           Email = '[email protected]',
                           Username = '[email protected]',
                           ProfileId = profileId.id,
                           TimeZoneSidKey = 'GMT',
                           LanguageLocaleKey = 'en_US',
                           EmailEncodingKey = 'UTF-8',
                           LocaleSidKey = 'en_US'
                           );

        Profile profileId2 = [SELECT Id FROM Profile WHERE Name = 'Staff HPL' LIMIT 1];
        User usr2 = new User(LastName = 'LIVESTON2',
                           FirstName='JASON2',
                           Alias = 'jliv2',
                           Email = '[email protected]',
                           Username = '[email protected]',
                           ProfileId = profileId2.id,
                           TimeZoneSidKey = 'GMT',
                           LanguageLocaleKey = 'en_US',
                           EmailEncodingKey = 'UTF-8',
                           LocaleSidKey = 'en_US'
                           );

        Named_User__c nu = new Named_User__c();
            nu.User__c = usr.id;    
            nu.name = 'test';
            nu.First_Name__c = 'test';
            nu.Email__c = '[email protected]';
            nu.First_Name__c = 'test';
            insert nu;  

        Named_User__c nu2 = new Named_User__c();
            nu2.User__c = usr2.id;    
            nu2.name = 'test';
            nu2.First_Name__c = 'test';
            nu2.Email__c = '[email protected]';
            nu2.First_Name__c = 'test';
            insert nu2;  

        Master_VIP_Segmentasi__c seg = new Master_VIP_Segmentasi__c();
            seg.Rangking_From_1__c = 1;
            insert seg;

        Account acc = new Account();
            acc.Named_User__c = nu.id;
            acc.Company_Type__c = 'PT';
            acc.Name = 'test Village';
            acc.Customer_Group__c = 'BUMN';
            acc.Company_Birthday__c = date.today();
            acc.Company_Establishment_Deed__c = date.today();
            acc.Joining_Since__c = date.today();
            acc.Rangking__c = seg.Rangking_From_1__c;
            Insert acc;

         Billing_Account__c ba = new Billing_Account__c();
            ba.Account__c = acc.id;
            ba.name = 'billing name';
            ba.Branch__c = 'Tanjung Priok';
            insert ba;

        Contact cc = new Contact();
            cc.LastName = 'test';
            cc.AccountId = acc.id;
            cc.MobilePhone = '12312313';
            cc.Email = '[email protected]';
            cc.Birthdate = date.today()-365;
            insert cc;

        Custom_Emaill_Log__c newCEL1 = new Custom_Emaill_Log__c();
                newCEL1.Contact__c = cc.id;
                newCEL1.Customer__c = cc.AccountId;
                newCEL1.Email__c = cc.Email;
                newCEL1.Send_Date__c = cc.Birthdate;
                newCEL1.Status__c = 'Send';
                newCEL1.Tipe_Data__c = 'Contact';
                newCEL1.Actual_Send_Date__c = date.today();
                insert newCEL1; 

        Custom_Emaill_Log__c newCEL2 = new Custom_Emaill_Log__c();
                newCEL2.Contact__c = cc.id;
                newCEL2.Customer__c = cc.AccountId;
                newCEL2.Email__c = cc.Email;
                newCEL2.Send_Date__c = cc.Birthdate;
                newCEL2.Status__c = 'Send';
                newCEL2.Tipe_Data__c = 'Customer';
                newCEL2.Actual_Send_Date__c = date.today();
                insert newCEL2;  


        Test.startTest(); 

        String jobId = System.schedule('SendedEmail',
        SendedEmail.CRON_EXP, 
        new SendedEmail());

        Test.stopTest();
    }
}
8
  • Is the Profile__c field on Named_User__c a formula field? Commented Sep 12, 2018 at 11:39
  • @rael_kid yes it is Commented Sep 12, 2018 at 11:39
  • I use formula to get user__r.Profile.Name Commented Sep 12, 2018 at 11:40
  • Have you set the @isTest annotation with SeeAllData=true? ex: @isTest(SeeAllData=true) static void myTestMethod() { // TESTS } Commented Sep 12, 2018 at 14:44
  • How is the code being invoked? Can you include the remainder of this unit test and the surrounding context (method or class) of the tested code?
    – David Reed
    Commented Sep 12, 2018 at 22:14

1 Answer 1

2

It does not appear that you are inserting the User in your test class. You cannot access the Id of the record if it is not inserted. Add this after your user declaration:

try{
    insert usr;
}
catch( Exception ex ){
    System.debug( 'Error inserting test user: ' + ex.getMessage() );
}

System.assertNotEquals( null, usr.Id );

OR add both of your users to a list and insert them together. Might be beneficial to add a setup method for the User inserts to avoid errors inserting other records after.

@TestSetup
static void setupMyUsers(){
  .... My user insert codes....
}

static testMethod void MyTestMethod(){
    ... Query for my users inserted here...
    List<User> myUsers = [ SELECT Id, Profile.Name FROM User ];
    System.assertEquals( <list size expected>, myUsers.size() );
    ... Handle my other data ...
}
3
  • I guess i need a better glasses.. hahaha.. thanks Ronnie! Commented Sep 13, 2018 at 4:18
  • no problem! i hope this solves it for you. If so, please accept my answer so other's may benefit.
    – Ronnie
    Commented Sep 13, 2018 at 4:21
  • 2
    You will not be able to insert Custom objects after the User objects if within the test method, which is why i suggest to insert the users in a setup method so that you can access their Ids for your other object inserts in the actual test method. The DML will happen in two separate context that way and be safe. - or if you decide to do both in the test method, use System.RunAs before inserting other data
    – Ronnie
    Commented Sep 13, 2018 at 4:26

You must log in to answer this question.

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