function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Sudipta DebSudipta Deb 

Apex Specialist Superbadge || Getting error when writing the unit test (300 Maintenance Requests)

Hi All -

I have the below code for which I am trying to write the test method to test the bulkify of my code (with 300 Maintenance Requests)

Maintenance Request Helper:
public class MaintenanceRequestHelper {
    private static List<Case> closedCases = new List<Case>();
    private static List<Case> newlyCreatedCases = new List<Case>();
    private static List<Work_Part__c> allWorkParts = new List<Work_Part__c>();
    

    public static void updateAfterUpdateActivity(List<Case> newCases, Map<Id, Case> oldCases){
    	System.Debug('SUDIPTA- CALLED FOR: ' + newCases.size());
    	for(Case singleCase : newCases){
	    	if(singleCase.status == 'Closed' && oldCases.get(singleCase.ID).status != singleCase.status){
	    		if(singleCase.Type == 'Repair' || singleCase.Type == 'Routine Maintenance'){
	    			closedCases.add(singleCase);
	       		}
	    	}
	    }
	    createFollowUpMaintenanceRequest();
    }

    private static void createFollowUpMaintenanceRequest(){
    	Set<ID> caseIds = new Set<ID>();
    	for(Case singleCase : closedCases){
    		caseIds.add(singleCase.Id);
    	}
    	Integer shortestMaintCycle;
    	
    	Map<Id, List<Work_Part__c>> maintWorkPartMap = createMaintWorkPartMap(caseIds);

    	for(Case singleCase : closedCases){
    		List<Work_Part__c> workParts = maintWorkPartMap.get(singleCase.Id);
    		if(workParts != null){
    			shortestMaintCycle = Integer.valueOf(findShortestMaintCycle(workParts));	
    		}else{
    			shortestMaintCycle = Integer.valueOf(0.0);
    		}
    		

    		Case newCase = new Case();
    		newCase.Vehicle__c = singleCase.Vehicle__c;
    		newCase.Type = 'Routine Maintenance';
    		newCase.status = 'New';
    		newCase.Origin = singleCase.Origin;
    		newCase.Reason = singleCase.Reason;
    		newCase.Subject = String.isBlank(singleCase.Subject) ? 'Routine Maintenance Request' :
    			singleCase.Subject;
    		newCase.Date_Reported__c = Date.today();
    		newCase.Date_Due__c = Date.today().addDays(shortestMaintCycle);
    		newCase.Equipment__c = singleCase.Equipment__c;
    		//newCase.Old_Case__c = 'OldCase-'+String.valueOf(singleCase.Id);
    		//newCase.Old_Case__c = singleCase.Case_Id_String__c;
    		newlyCreatedCases.add(newCase);
    	}

    	if(newlyCreatedCases.size() > 0){
    		insert newlyCreatedCases;
    		//updateRelatedWorkOrders(newlyCreatedCases);
    	}
    }
    
    private static void updateRelatedWorkOrders(List<Case> cases){
    	Map<String, Id> oldToNewCaseMap = new Map<String, Id>();
    	for(Case singleCase : cases){
    		oldToNewCaseMap.put(singleCase.Old_Case__c,singleCase.Id);
    	}

    	if(allWorkParts != null){
    		for(Work_Part__c singleWorkPart : allWorkParts){
    			//String key = 'OldCase-'+String.valueOf(singleWorkPart.Maintenance_Request__c);
    			String key = String.valueOf(singleWorkPart.Maintenance_Request__c);
    			Id newCaseId = oldToNewCaseMap.get(singleWorkPart.Maintenance_Request__c);
    			singleWorkPart.Maintenance_Request__c = newCaseId;
    		}
    	}

    	if(allWorkParts != null && allWorkParts.size() > 0){
    		update allWorkParts;
    	}
    }

    private static Decimal findShortestMaintCycle(List<Work_Part__c> workParts){
    	Decimal shortestValue;
    	if(workParts.size()>0){
    		shortestValue = workParts.get(0).Equipment__r.Maintenance_Cycle__c;
    	}
    	for(Work_Part__c singleWorkPart : workParts){
    		if(singleWorkPart.Equipment__r.Maintenance_Cycle__c < shortestValue){
    			shortestValue = singleWorkPart.Equipment__r.Maintenance_Cycle__c;
    		}
    	}
    	return shortestValue;
    }

    private static Map<Id, List<Work_Part__c>> createMaintWorkPartMap(Set<ID> caseIds){
    	//Fetch all WorkPart details
    	allWorkParts = [SELECT ID, Equipment__c, Maintenance_Request__c, 
    			Quantity__c, Equipment__r.Maintenance_Cycle__c FROM Work_Part__c 
    			WHERE Maintenance_Request__c in: caseIds];
    	Map<Id, List<Work_Part__c>> maintWorkPartMap = new Map<Id, List<Work_Part__c>>();
    	for(Work_Part__c singleWorkPart : allWorkParts){
    		List<Work_Part__c> tempList;
    		if(maintWorkPartMap.get(singleWorkPart.Maintenance_Request__c) == null){
    			tempList = new List<Work_Part__c>();
    		}else{
    			tempList = maintWorkPartMap.get(singleWorkPart.Maintenance_Request__c);
    		}
    		tempList.add(singleWorkPart);
    		maintWorkPartMap.put(singleWorkPart.Maintenance_Request__c, tempList);
    	}

    	return maintWorkPartMap;
    }
    
}

And here is my test method-
@isTest
    static void test_Closing_300_Routine_Maintenance_should_create_300_New_Maint(){
    	//Arrange
    	Vehicle__c singleVehicle = TestDataFactory.createVehicle();
    	List<Product2> equipments = TestDataFactory.createEquipments();
    	List<Case> allMaintRequests = TestDataFactory.createMultipleMainRequestWith(
    					201,
    					singleVehicle,
    					'Routine Maintenance',
    					'Open',
    					'Email',
    					'Not Working',
    					'Not Working',
    					Date.today(),
    					Date.today().addDays(10),
    					equipments);
    	
    	//Act
    	Test.startTest();
    	for(Case singleMaintRequest : allMaintRequests){
    		singleMaintRequest.status = 'Closed';
    	}
    	update allMaintRequests;
    	Test.stopTest();			
    	
    	//Assert
    	//List<Case> allCases = [SELECT ID,Date_Due__c FROM Case WHERE Vehicle__c =: singleVehicle.Id and status = 'New'];
    	List<Case> allCases = [SELECT ID,Date_Due__c FROM Case WHERE status = 'New'];
    	System.assertEquals(201,allCases.size());	
    	
    }

Below is the error message I am getting -
System.DmlException: Update failed. First exception on row 200 with id 50036000003SeKQAA0; first error: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY, MaintenanceRequest: execution of AfterUpdate

caused by: System.DmlException: Insert failed. First exception on row 0 with id 50036000003SeKRAA0; first error: INVALID_FIELD_FOR_INSERT_UPDATE, cannot specify Id in an insert call: [Id]

Class.MaintenanceRequestHelper.createFollowUpMaintenanceRequest: line 54, column 1
Class.MaintenanceRequestHelper.updateAfterUpdateActivity: line 16, column 1
Trigger.MaintenanceRequest: line 3, column 1: []

Strange thing is that if I test with 200 Maintenance Requests, test method is getting passed, but the moment I make it 201, it started failing. Any idea why this is behaving like this?
Best Answer chosen by Sudipta Deb
Sudipta DebSudipta Deb
Finally I was able to fix that. The issue was happening due to the fact that I made the list newlyCreatedCases as static. That is why it was working till 200 records (Each trigger invocation will work with a maximum of 200 records). Right now I moved the static variable to local variable and also moved other static variables in the same way. After that I was able to complete the step.
Apex Superbadge

All Answers

Sudipta DebSudipta Deb
I commented out line#55 just to check whether new records are getting inserted or not. And I have noticed that problem is while inserting the new records,
Sudipta DebSudipta Deb
Finally I was able to fix that. The issue was happening due to the fact that I made the list newlyCreatedCases as static. That is why it was working till 200 records (Each trigger invocation will work with a maximum of 200 records). Right now I moved the static variable to local variable and also moved other static variables in the same way. After that I was able to complete the step.
Apex Superbadge
This was selected as the best answer
pandi GSpandi GS
Hi,
can you share the testDatafactory class?

Thanks