0

I'm building a batch class to update the WorkOrder. But I can't call the method execute to test this part. How can I test my logic inside the try in the execute method in batch classes?

global class Atualizar_Aging_OS_Batch implements Database.Batchable<sObject>, Database.AllowsCallouts, Database.Stateful {

        global final String query;

        global Atualizar_Aging_OS_Batch(String q){
            System.debug(LoggingLevel.ERROR, '___ [cls Atualizar_Aging_OS - construtor()] - Inicio... ');
            query = q;
        }

        /*
            Metodo start do batch
        */       
        global Database.QueryLocator start(Database.BatchableContext BC) {
            System.debug(LoggingLevel.ERROR, '___ [cls Atualizar_Aging_OS - start()] - Inicio... ');
            return Database.getQueryLocator(query);
        }

        /*
        Metodo execute, roda quando iniciar o Batch
        */        
        global void execute(Database.BatchableContext BC, List<WorkOrder> scope) {

            System.debug(LoggingLevel.ERROR, '___ [cls Atualizar_Aging_OS - execute()] - Inicio... ');

            List<WorkOrder> listOrdemServico = new List<WorkOrder>();

            try {

                for(sObject so : scope){

                    WorkOrder OS = (WorkOrder) so;

                    if(OS.EndDate == NULL){

                        DateTime hojeDateTime = System.now();
                        Date hoje = date.newinstance(hojeDateTime.year(), hojeDateTime.month(), hojeDateTime.day());
                        Date dataInicial = date.newinstance(OS.StartDate.year(), OS.StartDate.month(), OS.StartDate.day());
                        OS.Aging__c = dataInicial.daysBetween(hoje);
                    } else { 

                        DateTime hojeDateTime = System.now();
                        Date dataFinal = date.newinstance(OS.EndDate.year(), OS.EndDate.month(), OS.EndDate.day());
                        Date dataInicial = date.newinstance(OS.StartDate.year(), OS.StartDate.month(), OS.StartDate.day());
                        OS.Aging__c = dataInicial.daysBetween(dataFinal);
                    }

                    listOrdemServico.add(OS);     

                }

                if(listOrdemServico != null && listOrdemServico.size() > 0) update listOrdemServico;

            } catch(Exception e){

                System.debug(LoggingLevel.ERROR, '___ [cls Atualizar_Aging_OS - execute()] - ERROR: '+e.getMessage());
            }
        }

        global void finish(Database.BatchableContext BC) {}

    }

I've done a lot of modifications to the code of the testclass but I only get 22%, and the logic in the execute method I cannot validate.

@isTest
public class Teste_Atualizar_Aging_OS_Batch {


    public static WorkOrder criaOrderServico(String Cliente, Integer Aging) {

        // Método para retornar OS com a Data de Conclusão nula
        WorkOrder OS = new WorkOrder(); 
        DateTime hojeDateTime = System.now();
        Date hoje = date.newinstance(hojeDateTime.year(), hojeDateTime.month(), hojeDateTime.day());
        Date dataInicial = date.newinstance(OS.StartDate.year(), OS.StartDate.month(), OS.StartDate.day());
        Date dataFinal = date.newinstance(OS.EndDate.year(), OS.EndDate.month(), OS.EndDate.day());
        OS.Cliente__c = 'Cliente';
        OS.Codigo_Externo__c = 1234569;
        OS.StartDate = dataInicial;
        OS.EndDate = null;
        OS.Aging__c = Aging;

        insert OS;
        return OS;       
    } // Fim método criaOrdemServico

    // Método testa OSs com Data de Conclusão nulas
    static testMethod Void testeConclusaoNula() {

        Test.startTest();

        Atualizar_Aging_OS_Batch aging = new Atualizar_Aging_OS_Batch('SELECT Id ' +
                                                                      ', StartDate ' +
                                                                      ', EndDate ' +
                                                                      ', Aging__c ' + 
                                                                      'FROM WorkOrder ');
        Id batchId = Database.executeBatch(aging);  

        Test.stopTest();
    }

    public static testMethod void testBatch() {

        Test.startTest();

        Atualizar_Aging_OS_Batch aaob = new Atualizar_Aging_OS_Batch(
            'SELECT Id ' +
            ', StartDate ' +
            ', EndDate ' +
            ', Aging__c ' + 
            'FROM WorkOrder ' +
            'WHERE (EndDate = null)');
        Id batchId = Database.executeBatch(aaob);

        Test.stopTest();

        System.assertEquals(10, [select count() from WorkOrder where Gerada_por__c = 'teste']);
    }
}
0

You have to create test data for your batch to iterate over. See the Apex Developer Guide (emphasis mine):

Isolation of Test Data from Organization Data in Unit Tests

Starting with Apex code saved using Salesforce API version 24.0 and later, test methods don’t have access by default to pre-existing data in the organization, such as standard objects, custom objects, and custom settings data, and can only access data that they create. However, objects that are used to manage your organization or metadata objects can still be accessed in your tests such as:

  • User
  • Profile
  • Organization
  • AsyncApexJob
  • CronTrigger
  • RecordType
  • ApexClass
  • ApexTrigger
  • ApexComponent
  • ApexPage

Whenever possible, you should create test data for each test. You can disable this restriction by annotating your test class or test method with the IsTest(SeeAllData=true) annotation.

Test code saved using Salesforce API version 23.0 or earlier continues to have access to all data in the organization and its data access is unchanged.

So each test needs to run some variation of:

List<WorkOrder> recordsToIterateOver = new List<WorkOrder>();
// add records to collection
insert recordsToIterateOver;

Test.startTest();
    // execute batch
Test.stopTest();

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.