0

I have a test class that seems not to be inserting some setup objects I need for the test.

My test class is as follows:

@isTest(seealldata=false) private class Alertas_The_Influence_isTest{ 
public static String CRON_EXP = '0 0 0 15 3 ? 2022'; @testsetup static void createtestdata(){
System.runAs ( new User(Id = UserInfo.getUserId()) ) {

UserRole rol1 = new UserRole();
rol1.Name     = 'Tech Ninja'; 
UserRole rol2 = new UserRole();
rol2.Name     = 'Success Manager';
UserRole rol3 = new UserRole();
rol3.Name     = 'Inside Sales';
UserRole rol4 = new UserRole();
rol4.Name     = 'Country Manager';
UserRole rol5 = new UserRole();
rol5.Name     = 'Head of Challenges';
UserRole rol6 = new UserRole();
rol6.Name     = 'Asistente Administrativo';
UserRole rol7 = new UserRole();
rol7.Name     = 'Head of IT';

insert rol1;
insert rol2;
insert rol3;
insert rol4;
insert rol5;
insert rol6;
insert rol7;

user u = new user();
u.LastName = 'Test Code';
u.Email = 'test@test.com';
u.Alias = 'Tcode1';
u.Username = Crypto.getRandomLong()+'@'+Crypto.getRandomLong()+'.abc';
u.CommunityNickname = 'test121';
u.LocaleSidKey = 'en_US';
u.TimeZoneSidKey = 'GMT';
u.ProfileID = '00e36000000ao2F';
u.LanguageLocaleKey = 'en_US';
u.EmailEncodingKey = 'UTF-8';
u.UserRoleID = rol1.id;
insert u;

user us = new user();
us.LastName = 'Test Code';
us.Email = 'test@test.com';
us.Alias = 'Tcode2';
us.Username = Crypto.getRandomLong()+'@'+Crypto.getRandomLong()+'.abc';
us.CommunityNickname = 'test122';
us.LocaleSidKey = 'en_US';
us.TimeZoneSidKey = 'GMT';
us.ProfileID = '00e36000000ao2F';
us.LanguageLocaleKey = 'en_US';
us.EmailEncodingKey = 'UTF-8';
us.UserRoleID = rol3.id;
insert us;

user use = new user();
use.LastName = 'Test Code';
use.Email = 'test@test.com';
use.Alias = 'Tcode3';
use.Username = Crypto.getRandomLong()+'@'+Crypto.getRandomLong()+'.abc';
use.CommunityNickname = 'test123';
use.LocaleSidKey = 'en_US';
use.TimeZoneSidKey = 'GMT';
use.ProfileID = '00e36000000ao2F';
use.LanguageLocaleKey = 'en_US';
use.EmailEncodingKey = 'UTF-8';
use.UserRoleID = rol6.id;
insert use;

user usi = new user();
usi.LastName = 'Test Code';
usi.Email = 'test@test.com';
usi.Alias = 'Tcode4';
usi.Username = Crypto.getRandomLong()+'@'+Crypto.getRandomLong()+'.abc';
usi.CommunityNickname = 'test1234';
usi.LocaleSidKey = 'en_US';
usi.TimeZoneSidKey = 'GMT';
usi.ProfileID = '00e36000000ao2F';
usi.LanguageLocaleKey = 'en_US';
usi.EmailEncodingKey = 'UTF-8';
usi.UserRoleID = rol7.id;
insert usi;



task ta         = new task();
ta.OwnerID      = u.Id;
ta.ActivityDate = Date.Today();
ta.Status       = 'Open';
insert ta;


task tai         = new task();
tai.OwnerID      = usi.Id;
tai.ActivityDate = Date.Today();
tai.Status       = 'Open';
insert tai;    

task tas         = new task();
tas.OwnerID      = us.Id;
tas.ActivityDate = Date.Today();
tas.Status       = 'Open';   
insert tas;

task tas1         = new task();
tas1.OwnerId      = use.Id;
tas1.ActivityDate = Date.Today();
tas1.Status       = 'Open';  
insert tas1;


task tas2              = new task();
tas2.OwnerId           = u.Id;
tas2.ActivityDate      = Date.Today();
tas2.Status            = 'Completed'; 
tas2.Task_Terminado__c = Date.Today();
tas2.DEMO_BANT__c      = TRUE;
insert tas2; 
}
}
static testmethod void test1(){
Test.startTest();
    system.schedule('test job', CRON_EXP, new Alertas_The_Influence());
Test.stopTest();
}
}

The issue here is that when I run the test, the queries on my tested class should return the tasks I created on the test class but return a size 0 list like if the tasks where never inserted. I use the System.runAs method to escape a DML error. What could be happening here?

Here's my class:

global class Alertas_The_Influence implements Schedulable {
global void execute(SchedulableContext SC) {

    UserRole Tech_Ninja                = [SELECT Id from UserRole where Name='Tech Ninja' limit 1];
    UserRole Success_Manager           = [SELECT Id from UserRole where Name='Success Manager' limit 1];
    UserRole Inside_Sales              = [SELECT Id from UserRole where Name='Inside Sales' limit 1];
    UserRole Country_Manager           = [SELECT Id from UserRole where Name='Country Manager' limit 1];
    UserRole Head_Challenges           = [SELECT Id from UserRole where Name='Head of Challenges' limit 1];
    UserRole Asistente_Administrativo  = [SELECT Id from UserRole where Name='Asistente Administrativo' limit 1];
    UserRole Head_IT                   = [SELECT Id from UserRole where Name='Head of IT' limit 1];


    List <User> Servicio  = [Select ID, Name From User Where IsActive=TRUE And (UserRoleId =: tech_Ninja.Id OR UserRoleId =: Success_Manager.Id)];
    List <User> Comercial = [Select ID, Name From User Where IsActive=TRUE And (UserRoleId =: Inside_Sales.Id OR UserRoleId =: Country_Manager.Id or UserRoleId =: Head_Challenges.Id)];
    List <User> Admin     = [Select ID, Name From User Where IsActive=TRUE And UserRoleId =: Asistente_Administrativo.Id];
    User IT               = [Select ID, Name From User Where IsActive=TRUE And UserRoleId =: Head_IT.Id limit 1];

    List<List<Task>> Tareas_Servicio = new List<List<Task>>();
    For (User Us : Servicio){
        List <Task> ta = [Select Id, ActivityDate, Who.name, subject, status, OwnerId, Owner.name From task Where ActivityDate=:Date.today() and OwnerId=:us.id and status!='Completed'];
        if (!ta.isEmpty()){
            Tareas_Servicio.add(ta); 
        }
    }  

    List<List<Task>> Tareas_Comercial = new List<List<Task>>();
    For (User Us : Comercial){
        List <Task> ta = [Select Id, ActivityDate,Who.name, subject, status, OwnerId, Owner.name From task Where ActivityDate=:Date.today() and OwnerId=:us.id and status!='Completed'];
        if (!ta.isEmpty()){
            Tareas_Comercial.add(ta);

        }

    }

    List<List<Task>> Tareas_Admin = new List<List<Task>>();
    For (User Us : Admin){
        List <Task> ta = [Select Id, ActivityDate, Who.name, subject, status, OwnerId, Owner.name From task Where ActivityDate=:Date.today() and OwnerId=:us.id and status!='Completed'];
        if (!ta.isEmpty()){
            Tareas_Admin.add(ta);
        }

    }

    integer  dia_mes    = Date.today().day();
    Datetime dia        = Date.Today();
    string   dia_semana = dia.format('u');
    String[] toAddresses1 = new String[] {'jcampo@theinfluence.co'};
    String[] toAddresses2 = new String[] {'jvaldes@theinfluence.co'};
    String[] toAddresses3 = new String[] {'e@theinfluence.co'};    
    string subject = 'Tareas Incompletas Departamento Comercial<br/><br/>';
    Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();

    list <task> TIT = [Select Id, ActivityDate, Who.name, subject, status, OwnerId, Owner.name From task Where ActivityDate=:Date.today() and OwnerId=:IT.id and status!='Completed'];
    if(TIT.size()>0){
        mail.setToAddresses(toAddresses3);  
        mail.setSenderDisplayName('Alertas The Influence');
        mail.setSubject('Alerta Tareas Incompletas IT ');
        subject = 'Tareas Incompletas IT <br/><br/>Victor: '+TIT.size();
        subject = subject+'<br/><br/>Haz click <a href= "https://theinfluence.my.salesforce.com/00O36000007EfAH" target="_blank">aquí</a> para ver el reporte.';    
        mail.setHtmlBody(subject);
        Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });

    }

            for (integer k = 0;k < Tareas_Comercial.size(); k++){
                if(Tareas_Comercial[k].size()>0) {
                    string nombre = Tareas_Comercial[K][0].Owner.name;
                    subject = subject + nombre + ': ' + Tareas_Comercial[k].size()+'<br/>';    

                }
            }
    if(Tareas_Comercial.size()>0){

                    mail.setToAddresses(toAddresses1);
                    mail.setCCAddresses(toAddresses2);  
                    mail.setSenderDisplayName('Alertas The Influence');
                    mail.setSubject('Alerta Tareas Incompletas Comercial ');
                    subject = subject+'<br/><br/>Haz click <a href= "https://theinfluence.my.salesforce.com/00O36000007EfAH" target="_blank">aquí</a> para ver el reporte.';    
                    mail.setHtmlBody(subject);
                    Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });

    }


            subject = 'Tareas Incompletas Departamento Servicio<br/><br/>';
            for (integer k = 0;k < Tareas_Servicio.size(); k++){
                if(Tareas_Servicio[k].size()>0) {
                    string nombre = Tareas_Servicio[K][0].Owner.name;
                    subject = subject + nombre + ': ' + Tareas_Servicio[k].size()+'<br/>';  

                }
            }

    If(Tareas_Servicio.size()>0){

                    mail.setToAddresses(toAddresses3);
                    mail.setCCAddresses(toAddresses2);  
                    mail.setSenderDisplayName('Alertas The Influence');
                    mail.setSubject('Alerta Tareas Incompletas Servicio');
                    subject = subject+'<br/><br/>Haz click <a href= "https://theinfluence.my.salesforce.com/00O36000007EfB0" target="_blank">aquí</a> para ver el reporte.';    
                    mail.setHtmlBody(subject); 
                    Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });         
    }

            subject = 'Tareas Incompletas Departamento Admin<br/><br/>';
            for (integer k = 0;k < Tareas_Admin.size(); k++){
                if(Tareas_Admin[k].size()>0) {
                    string nombre = Tareas_Admin[K][0].Owner.name;
                    subject = subject + nombre + ': ' + Tareas_Admin[k].size()+'<br/>';  

                }
            }
    if(Tareas_Admin.size()>0){

                    mail.setToAddresses(toAddresses3);
                    mail.setCCAddresses(toAddresses2);  
                    mail.setSenderDisplayName('Alertas The Influence');
                    mail.setSubject('Alerta Tareas Incompletas Admin');
                    subject = subject+'<br/><br/>Haz click <a href= "https://theinfluence.my.salesforce.com/00O36000007EfVo" target="_blank">aquí</a> para ver el reporte.';    
                    mail.setHtmlBody(subject);
                    Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });

    }

        List <Task> Demos = [Select Id, ActivityDate, Who.name, subject, status, OwnerId, Task_Terminado__c, DEMO_BANT__c From Task Where Status='Completed' and Task_Terminado__c=:Date.today() and DEMO_BANT__c=TRUE];

    IF(Demos.size()<3){
        String[] toAddresses4 = new String[] {'jcampo@theinfluence.co'};
        subject = 'No se llegaron a marcar 3 demos el dia de hoy<br/><br/>';           
        mail.setToAddresses(toAddresses4);
        mail.setCCAddresses(toAddresses4);  
        mail.setSenderDisplayName('Alertas The Influence');
        mail.setSubject('Alerta Demos Inside Sales');
        mail.setHtmlBody(subject);
        Messaging.sendEmail(new Messaging.SingleEmailMessage[] {mail});

    }



}

}
  • So you have a problem with a query but out of all the code you posted the query that you are having the problem with is missing? – Eric Aug 28 '17 at 21:50
  • @Eric Thanks for answering. The thing is that the query on my class really has no issue. I run the class on my sandbox and it works perfectly. The issue is with the test class since it seems that it's not inserting the tasks that match my query criteria. I can post my class if that helps. – Victor Echeverría Aug 28 '17 at 22:06
  • How do we know what the criteria is if we do not even know what the query is? – Eric Aug 28 '17 at 22:07
  • @Eric I added the class. It's a relatively simple query that works perfectly on my sandbox. – Victor Echeverría Aug 28 '17 at 22:09
  • Do those user roles already exist in your org, if so suprised you are not getting an error when you try to insert? Most likely the Id of the Users you are returning in your class (You limit to 1) are not any of the users you create in the test method and thus no tasks are returned. Debug the UserNames in the class and see if any are your test users – Eric Aug 28 '17 at 22:46
1

I just ran your code with this change to the test method:

static testmethod void test1() {
    Test.startTest();
    System.assertEquals(5, [select count() from Task]);
    // system.schedule('test job', CRON_EXP, new Alertas_The_Influence());
    Test.stopTest();
}

that demonstrates that the Tasks are being created and are visible in the test method. So the problem lies in Alertas_The_Influence class you are testing (and did not post in your question) not the test class.

(I did also check that the assertion runs and passes if done in a Schedulable.)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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