Superbadge Apex Specialist Full Solutions

Table of Contents
Challenge 1: Automate record creation
Challenge 2: Synchronize Salesforce data with an external system
Challenge 3: Schedule synchronization
Challenge 4: Test automation logic
Challenge 5: Test callout logic
Challenge 6: Test scheduling logic

Superbadge Apex Specialist looks good on Resume, and they prove worth it as well. You should definitely complete the task on your own and you can get all the help. All these codes are working 100% and run smoothly to help you achieve the below shiny badge. I had mine and wrote this while doing so…

Free Salesforce Exam Coupon Codes for 2022

Superbadge Apex Specialist

Apex Specialist

What You’ll Be Doing to Earn This Superbadge

  1. Automate record creation using Apex triggers
  2. Synchronize Salesforce data with an external system using asynchronous REST callouts
  3. Schedule synchronization using Apex code
  4. Test automation logic to confirm Apex trigger side effects
  5. Test integration logic using callout mocks
  6. Test scheduling logic to confirm action gets queued

Challenge 1: Automate record creation

Stuck on Superbadge Apex Specialist Step 1?

Change the labels for Case and Product To Maintenance Request and Equipment respectively.

Change the labels for Standard Objects and Fields in Salesforce
Go to Setup -> Customize -> Tab Names and Labels -> Rename Tabs and Labels.
Choose the Tab (or Object) you want to rename and click Edit.

Change the Codes
Go to Developer console and edit the Apex class and related triggers for below:

public with sharing class MaintenanceRequestHelper {
    public static void updateWorkOrders(List<Case> caseList) {
        List<case> newCases = new List<Case>();
        Map<String,Integer> result=getDueDate(caseList);
        for(Case c : caseList){
            if(c.status=='closed')
                if(c.type=='Repair' || c.type=='Routine Maintenance'){
                    Case newCase = new Case();
                    newCase.Status='New';
                    newCase.Origin='web';
                    newCase.Type='Routine Maintenance';
                    newCase.Subject='Routine Maintenance of Vehicle';
                    newCase.Vehicle__c=c.Vehicle__c;
                    newCase.Equipment__c=c.Equipment__c;
                    newCase.Date_Reported__c=Date.today();
                    if(result.get(c.Id)!=null)
                     newCase.Date_Due__c=Date.today()+result.get(c.Id);
                    else
                        newCase.Date_Due__c=Date.today();
                    newCases.add(newCase);
                }
        }        
        insert newCases;   
    }
    //
    public static  Map<String,Integer> getDueDate(List<case> CaseIDs){       
       Map<String,Integer> result = new Map<String,Integer>();
        Map<Id, case> caseKeys = new Map<Id, case> (CaseIDs);        
       List<AggregateResult> wpc=[select Maintenance_Request__r.ID cID,min(Equipment__r.Maintenance_Cycle__c)cycle
                      from Work_Part__c where  Maintenance_Request__r.ID in :caseKeys.keySet() group by             Maintenance_Request__r.ID ];
        for(AggregateResult res :wpc){
            Integer addDays=0;
            if(res.get('cycle')!=null)
                addDays+=Integer.valueOf(res.get('cycle'));
            result.put((String)res.get('cID'),addDays);
        }
        return result;
}
}
trigger MaintenanceRequest on Case (before update, after update) {
    // ToDo: Call MaintenanceRequestHelper.updateWorkOrders
       if(Trigger.isAfter)
                 MaintenanceRequestHelper.updateWorkOrders(Trigger.New);
                
            
    }

Challenge 2: Synchronize Salesforce data with an external system

Issue with Superbadge Apex Specialist Step 2?

public with sharing class WarehouseCalloutService {
    private static final String WAREHOUSE_URL = 'https://th-superbadge-apex.herokuapp.com/equipment';
    
    @future(callout=true)
    public static void runWarehouseEquipmentSync() {
        //ToDo: complete this method to make the callout (using @future) to the
        //      REST endpoint and update equipment on hand.
    
		
		HttpResponse response = getResponse(); 
        if(response.getStatusCode() == 200)
        {
            List<Product2> results = getProductList(response); //get list of products from Http callout response
            
            if(results.size() >0)
            upsert results Warehouse_SKU__c; //Upsert the products in your org based on the external ID SKU
        }
        
    }
        //Get the product list from the external link
        public static List<Product2> getProductList(HttpResponse response)
        {
            
            List<Object> externalProducts = (List<Object>) JSON.deserializeUntyped(response.getBody()); //desrialize the json response
            List<Product2> newProducts = new List<Product2>();
            
            for(Object p : externalProducts)
            {
                Map<String, Object> productMap = (Map<String, Object>) p;
                Product2 pr = new Product2();
            	//Map the fields in the response to the appropriate fields in the Equipment object
                pr.Replacement_Part__c = (Boolean)productMap.get('replacement');
                pr.Cost__c = (Integer)productMap.get('cost');
                pr.Current_Inventory__c = (Integer)productMap.get('quantity');
                pr.Lifespan_Months__c = (Integer)productMap.get('lifespan') ;
                pr.Maintenance_Cycle__c = (Integer)productMap.get('maintenanceperiod');
                pr.Warehouse_SKU__c = (String)productMap.get('sku');
                pr.ProductCode = (String)productMap.get('_id');
                pr.Name = (String)productMap.get('name');
                
            
                newProducts.add(pr);
            }
            
            return newProducts;
            
        }
        
        // Send Http GET request and receive Http response
    
    public static HttpResponse getResponse() {
        
        Http http = new Http();
        HttpRequest request = new HttpRequest();
        request.setEndpoint(WAREHOUSE_URL);
        request.setMethod('GET');
        HttpResponse response = http.send(request);
        
        return response;
        
    }
    }

Execute below in the anonymous window : 

WarehouseCalloutService.runWarehouseEquipmentSync(); 

Wait for a minute and run it twice maybe before checking challenges.

Challenge 3: Schedule synchronization

Help with Superbadge Apex Specialist Step 3?

Go to Setup > Apex Classes > Schedule a job like below:

Superbadge Apex Specialist solutions

Edit the following in the Developer console

global  class WarehouseSyncSchedule implements Schedulable{
    // implement scheduled code here
    global  void execute (SchedulableContext sc){
        
        WarehouseCalloutService.runWarehouseEquipmentSync();
        //optional this can be done by debug mode 
       String sch = '00 00 01 * * ?';//on 1 pm 
       System.schedule('WarehouseSyncScheduleTest', sch, new WarehouseSyncSchedule());
         
           
    }
}

And execute in the anonymous window below: 

WarehouseSyncSchedule scheduleInventoryCheck();

Read More: Salesforce Interview Questions and Answers We Swear By!

Challenge 4: Test automation logic

Stuck on Superbadge Apex Specialist Step 4?

Modifications to the below Apex Classes as below.

trigger MaintenanceRequest on Case (before update, after update) {
 if(Trigger.isUpdate && Trigger.isAfter)
  MaintenanceRequestHelper.updateWorkOrders(Trigger.New);
}
@IsTest
private class InstallationTests {
    private static final String STRING_TEST = 'TEST';
    private static final String NEW_STATUS = 'New';
    private static final String WORKING = 'Working';
    private static final String CLOSED = 'Closed';
    private static final String REPAIR = 'Repair';
    private static final String REQUEST_ORIGIN = 'Web';
    private static final String REQUEST_TYPE = 'Routine Maintenance';
    private static final String REQUEST_SUBJECT = 'AMC Spirit';
    public static String CRON_EXP = '0 0 1 * * ?';
    
    static testmethod void testMaintenanceRequestNegative() {
        Vehicle__c vehicle = createVehicle();
        insert vehicle;
        Id vehicleId = vehicle.Id;
        Product2 equipment = createEquipment();
        insert equipment;
        Id equipmentId = equipment.Id;
        Case r = createMaintenanceRequest(vehicleId, equipmentId);
        insert r;
        Work_Part__c w = createWorkPart(equipmentId, r.Id);
        insert w;
        Test.startTest();
        r.Status = WORKING;
        update r;
        Test.stopTest();
        List<case> allRequest = [SELECT Id
                                 FROM Case];
        Work_Part__c workPart = [SELECT Id
                                 FROM Work_Part__c
                                 WHERE Maintenance_Request__c =: r.Id];
        System.assert(workPart != null);
        System.assert(allRequest.size() == 1);
    }
    
    static testmethod void testWarehouseSync() {
        Test.setMock(HttpCalloutMock.class, new WarehouseCalloutServiceMock());
        Test.startTest();
        String jobId = System.schedule('WarehouseSyncSchedule',
                                       CRON_EXP, 
                                       new WarehouseSyncSchedule());   
        CronTrigger ct = [SELECT Id, CronExpression, TimesTriggered, NextFireTime
                          FROM CronTrigger
                          WHERE id = :jobId];
        System.assertEquals(CRON_EXP, ct.CronExpression);
        System.assertEquals(0, ct.TimesTriggered);
        Test.stopTest();
    }    
    private static Vehicle__c createVehicle() {
        Vehicle__c v = new Vehicle__c(Name = STRING_TEST);
        return v;
    }
    private static Product2 createEquipment() {
        Product2 p = new Product2(Name = STRING_TEST,
                                  Lifespan_Months__c = 10,
                                  Maintenance_Cycle__c = 10,
                                  Replacement_Part__c = true);
        return p;
    }
    private static Case createMaintenanceRequest(Id vehicleId, Id equipmentId) {
        Case c = new Case(Type = REPAIR,
                          Status = NEW_STATUS,
                          Origin = REQUEST_ORIGIN,
                          Subject = REQUEST_SUBJECT,
                          Equipment__c = equipmentId,
                          Vehicle__c = vehicleId);
        return c;
    }
    private static Work_Part__c createWorkPart(Id equipmentId, Id requestId) {
        Work_Part__c wp = new Work_Part__c(Equipment__c = equipmentId,
                                           Maintenance_Request__c = requestId);
        return wp;
    }
}
public with sharing class MaintenanceRequestHelper {
public static void updateWorkOrders(List<case> caseList) {
List<case> newCases = new List<case>();
Map<String,Integer> result=getDueDate(caseList);
for(Case c : caseList){
if(c.status=='closed')
if(c.type=='Repair' || c.type=='Routine Maintenance'){
Case newCase = new Case();
newCase.Status='New';
newCase.Origin='web';
newCase.Type='Routine Maintenance';
newCase.Subject='Routine Maintenance of Vehicle';
newCase.Vehicle__c=c.Vehicle__c;
newCase.Equipment__c=c.Equipment__c;
newCase.Date_Reported__c=Date.today();
if(result.get(c.Id)!=null)
newCase.Date_Due__c=Date.today()+result.get(c.Id);
else
newCase.Date_Due__c=Date.today();
newCases.add(newCase);
}
}
insert newCases;
}
//
public static  Map<String,Integer> getDueDate(List<case> CaseIDs){
Map<String,Integer> result = new Map<String,Integer>();
Map<Id, case> caseKeys = new Map<Id, case> (CaseIDs);
List<aggregateresult> wpc=[select Maintenance_Request__r.ID cID,min(Equipment__r.Maintenance_Cycle__c)cycle
from Work_Part__c where  Maintenance_Request__r.ID in :caseKeys.keySet() group by             Maintenance_Request__r.ID ];
for(AggregateResult res :wpc){
Integer addDays=0;
if(res.get('cycle')!=null)
addDays+=Integer.valueOf(res.get('cycle'));
result.put((String)res.get('cID'),addDays);
}
return result;
}
}
@isTest
public  class MaintenanceRequestTest {
     static  List<case> caseList1 = new List<case>();
   static List<product2> prodList = new List<product2>();
       static List<work_part__c> wpList = new List<work_part__c>();
@testSetup
    static void getData(){
      caseList1= CreateData( 300,3,3,'Repair');
    }
    
    public static List<case>   CreateData( Integer numOfcase, Integer numofProd, Integer numofVehicle,
                                String type){
 List<case> caseList = new List<case>();
        //Create Vehicle       
        Vehicle__c vc = new Vehicle__c();
        vc.name='Test Vehicle';
        upsert vc;
        //Create Equiment
        for(Integer i=0;i<numofProd;i++){
            Product2 prod = new Product2();
            prod.Name='Test Product'+i;
            if(i!=0)
             prod.Maintenance_Cycle__c=i;
            prod.Replacement_Part__c=true;
            prodList.add(prod);
        }
        upsert  prodlist;
        //Create Case
        for(Integer i=0;i< numOfcase;i++){
            Case newCase = new Case();
           newCase.Status='New';
                 newCase.Origin='web';
            if( math.mod(i, 2) ==0)
             newCase.Type='Routine Maintenance';
            else
               newCase.Type='Repair'; 
            newCase.Subject='Routine Maintenance of Vehicle' +i;
            newCase.Vehicle__c=vc.Id;
            if(i<numofProd)
             newCase.Equipment__c=prodList.get(i).ID;
            else 
                newCase.Equipment__c=prodList.get(0).ID;
           caseList.add(newCase);
        }
    upsert caseList;       
     for(Integer i=0;i<numofProd;i++){                           
         Work_Part__c wp = new Work_Part__c();
          wp.Equipment__c   =prodlist.get(i).Id   ; 
          wp.Maintenance_Request__c=caseList.get(i).id;
          wplist.add(wp) ;
          }
    upsert wplist;
        return caseList;              
    }
   
   
    public static testmethod void testMaintenanceHelper(){        
        Test.startTest();
        getData();
            for(Case cas: caseList1)   
                 cas.Status ='Closed';      
        update caseList1;  
        Test.stopTest();
    }
}

Challenge 5: Test callout logic

Issue with Superbadge Apex Specialist Step 5?

Modify the Apex Classes as below, save and run all.


@IsTest
private class WarehouseCalloutServiceTest {
    // implement your mock callout test here
    @isTest
    static void testWareHouseCallout(){       
        Test.setMock(HttpCalloutMock.class, new WarehouseCalloutServiceMock());
       WarehouseCalloutService.runWarehouseEquipmentSync();        
    }
}
@isTest
public class WarehouseCalloutServiceMock implements HTTPCalloutMock {
    
    // implement http mock callout
    public HTTPResponse respond (HttpRequest request){
        HttpResponse response = new HTTPResponse();
        response.setHeader('Content-type','application/json');
        response.setBody('[{"_id":"55d66226726b611100aaf741","replacement":false,"quantity":5,"name":"Generator 1000 kW","maintenanceperiod":365,"lifespan":120,"cost":5000,"sku":"100003"},{"_id":"55d66226726b611100aaf742","replacement":true,"quantity":183,"name":"Cooling Fan","maintenanceperiod":0,"lifespan":0,"cost":300,"sku":"100004"},{"_id":"55d66226726b611100aaf743","replacement":true,"quantity":143,"name":"Fuse 20A","maintenanceperiod":0,"lifespan":0,"cost":22,"sku":"100005"}]');
        response.setStatusCode(200);
        return response;
        
    }
}

Challenge 6: Test scheduling logic

Stuck on Superbadge Apex Specialist Step 6?

Modify as below

@isTest
private class WarehouseSyncScheduleTest {
 public static String CRON_EXP = '0 0 0 15 3 ? 2022';
    
    static testmethod void testjob(){
         MaintenanceRequestTest.CreateData( 5,2,2,'Repair');
        Test.startTest();
        Test.setMock(HttpCalloutMock.class, new WarehouseCalloutServiceMock());
        String joBID= System.schedule('TestScheduleJob', CRON_EXP, new WarehouseSyncSchedule());
       // List<Case> caselist = [Select count(id) from case where case]        
        Test.stopTest();
    }
}

Hope this helps!
Looking For? Superbadge Process Automation Specialist – Full Solutions

Share to someone in the Trailhead Community. Let’s grow together.

Need help on specific errors? Start a discussion in the forum to get straight-up answers.

Let the universe renounce some goodness to you 😇

Read More: Salesforce Interview Questions and Answers We Swear By!

87 thoughts on “Superbadge Apex Specialist Full Solutions”

    • Hey Nikhil. Its been long time I completed those quests. Could you please point out the specific line of the code where the function has been used for me to check and get back to you more quickly. Also some of the functions come predefined and it might be that as well.
      Alternatively you can join our telegram group for technical discussions among industry professionals

      Reply
    • Hey komal. Could you please point out the specifics. Its a pretty long post that i wrote quiet long time back. Can’t remember precisely. Would have to get back to you. Alternatively you can join our telegram group for technical discussions among industry professionals

      Reply
  1. Challenge Not yet complete… here’s what’s wrong:
    Inserting a new Maintenance Request of type ‘Routine Maintenance’ and then closing it did not create of a new Maintenance Request based upon the original record correctly. The challenge is expecting to find the closed Maintenance Request plus an ‘New’ Maintenance Request of type ‘Routine Maintenance’ with the same Vehicle as the closed one.

    challenge 1 error
    Please help me

    Reply
  2. Hi,
    For Challenge 1 I am getting error for some of the fields that they doesn’t exist like Vehicle__c, Equipment__c, Due_Date__c. (I have already renamed Case and Product objects)
    I am not able understand the issue, can you please help??

    Reply
  3. hi
    admin
    i wanted to excel myself in healthcloud domain of salesforce as i have started badges of that domain on trailhead
    which certification i should do to expertise myself in that domain

    Reply
    • Hi there Neha !
      Currently there aren’t any specific certification related to health cloud. I think you should focus on gaining more of hands on experiences in handling scenarios similar to those in health cloud domain. And I might not be the best to advice on that particular section. Hope it helps

      Reply
      • Hi Admin, following up on this comment. I don’t see why there would be a Equipment__c lookup established with the Maintenance Request (Case) Object here, since the ERD clearly shows that the link is with the Equipment Maintenance Item Object (which can be found in the related list). Most of the other answers I found online also keep pointing to this Equipment__c field, which doesn’t exist. Do we need to create this lookup relationship between Maintenance Request (Case) and Equipment (Product)?

        Reply
        • Hey Haja. Apologies for m caught quite off guard at this moment. But i will surely get back to you on this. I had cleared this superbadge way back in time would have to seriously redo it to understand what was done on this one. Getting so many queries on this one I will surely try prioritize. Thanks for your wonderful gesture of letting know

          Reply
  4. I tried to use your code as it is and it gives error…..For this superbadge I already read on 7th Dec that Superbadge challenge will be changed on 9th Dec and I am unaware about old superbadge so cant tell you what actual changes are.

    Reply
    • Hi Admin,
      I used this code for MaintenanceRequestHelper:

      public with sharing class MaintenanceRequestHelper {

      public static void updateWorkOrders(List caseList) {
      Map<Id,List> mapOldCasesWithItems = getItemsInOldCases(caseList);
      Map mapOldCasesWithNewCases = createNewCases(caseList);

      linkEquipmentsToNewCases(mapOldCasesWithItems,mapOldCasesWithNewCases);
      }

      private static Map<Id,List> getItemsInOldCases(List caseList){
      Set setIdCases = new Set();
      for(Case caseInList: caseList){
      setIdCases.add(caseInList.Id);
      }

      List lista = [
      SELECT Id, Maintenance_Request__c, Equipment__c , Quantity__c
      FROM Equipment_Maintenance_Item__c
      WHERE Maintenance_Request__c IN :setIdCases];

      Map<Id,List> mapCases = new Map<Id,List>();
      for(Equipment_Maintenance_Item__c item: lista){
      Id oldCaseId = item.Maintenance_Request__c;
      if (!mapCases.containsKey(oldCaseId)){
      mapCases.put(oldCaseId,new List());
      }
      mapCases.get(oldCaseId).add(item);
      }

      return mapCases;
      }

      private static Map createNewCases(List caseList) {
      Map newCases = new Map();
      Map result = getDueDate(caseList);

      for(Case oneCase : caseList) {
      if((oneCase.status==’closed’) && (oneCase.type==’Repair’ || oneCase.type==’Routine Maintenance’)) {
      Date newDate = Date.today();

      if(result.get(oneCase.Id)!=null) {
      newDate = Date.today()+result.get(oneCase.Id);
      }

      Case newRoutineCase = createNewMaintenanceCase(oneCase.Id, oneCase.Vehicle__c, newDate);
      newCases.put(oneCase.Id, newRoutineCase);
      }
      }

      List tmpCases = new List();
      Set oldIdCases = newCases.keySet();
      for(Id oldId : oldIdCases){
      tmpCases.add(newCases.get(oldId));
      }
      insert tmpCases;

      return newCases;
      }

      public static Map getDueDate(List CaseIDs) {
      Map result = new Map();
      Map caseKeys = new Map (CaseIDs);
      List wpc= [
      SELECT Maintenance_Request__r.ID cID, MIN(Equipment__r.Maintenance_Cycle__c)cycle
      FROM Equipment_Maintenance_Item__c where Maintenance_Request__r.ID in :caseKeys.keySet()
      GROUP BY Maintenance_Request__r.ID ];
      for(AggregateResult res :wpc){
      Integer addDays=0;
      if(res.get(‘cycle’)!=null){
      Integer daysToAdd = Integer.valueOf(res.get(‘cycle’));
      addDays+=daysToAdd;
      }
      result.put((Id)res.get(‘cID’),addDays);
      }
      return result;
      }

      static private Case createNewMaintenanceCase(Id oldCaseId,Id vehicle, Date newDate) {
      Case newCase = new Case();
      newCase.Status=’New’;
      newCase.Origin=’web’;
      newCase.Type=’Routine Maintenance’;
      newCase.Subject=’Routine Maintenance of Vehicle’;
      newCase.Vehicle__c=vehicle;
      newCase.Date_Reported__c=Date.today();
      newCase.Date_Due__c=newDate;

      return newCase;
      }

      private static void linkEquipmentsToNewCases(
      Map<Id,List> mapOldCasesWithItems, Map mapOldCasesWithNewCases){

      List listEquipmentMaintenanceItem =
      new List();
      Set idOldCases = mapOldCasesWithNewCases.keySet();
      for(Id idOld : idOldCases){
      Case newCase = mapOldCasesWithNewCases.get(idOld);
      List items = mapOldCasesWithItems.get(idOld);
      for(Equipment_Maintenance_Item__c item : items){
      Equipment_Maintenance_Item__c newItem = new Equipment_Maintenance_Item__c();
      newItem.Quantity__c = item.Quantity__c;
      newItem.Maintenance_Request__c = newCase.Id;

      listEquipmentMaintenanceItem.add(newItem);
      }
      }

      insert listEquipmentMaintenanceItem;
      }

      }

      It’s not optimized but it gives me 500 points, and it is good! 😀

      Reply
      • Code for challenge 4:

        @isTest
        public with sharing class MaintenanceRequestHelperTest {

        public static Vehicle__c buildVehicle(){
        Vehicle__c newVehicle = new Vehicle__c();
        newVehicle.Name = ‘Dummy Vehicle’;

        return newVehicle;
        }

        public static Product2 buildEquipment(){
        Product2 newEquipment = new Product2();
        newEquipment.Name = ‘Dummy Equipment’;
        newEquipment.Lifespan_Months__c = 10;
        newEquipment.Maintenance_Cycle__c = 10;
        newEquipment.Replacement_Part__c = true;

        return newEquipment;
        }

        public static Case buildCase(Id vehicleId, String typeCase, String subjectCase){
        Case newCase = new Case();
        newCase.Status=’closed’;
        newCase.Origin=’web’;
        newCase.Type=typeCase;
        newCase.Subject=subjectCase;
        newCase.Vehicle__c=vehicleId;
        newCase.Date_Reported__c=Date.today();
        newCase.Date_Due__c=Date.today();

        return newCase;
        }

        public static Equipment_Maintenance_Item__c buildItem(Id caseId, Id equipmentId){
        Equipment_Maintenance_Item__c newItem = new Equipment_Maintenance_Item__c();
        newItem.Quantity__c = 10;
        newItem.Maintenance_Request__c = caseId;
        newItem.Equipment__c = equipmentId;

        return newItem;
        }

        @TestSetup
        public static void setupTest(){
        Vehicle__c vehicle = buildVehicle();
        insert vehicle;
        Product2 equipment = buildEquipment();
        insert equipment;

        List newCases = new List();
        for(Integer i_ok = 0; i_ok < 300; i_ok ++){
        Case newCase = buildCase(vehicle.Id,'Repair','DummyOK_'+i_ok);
        newCases.add(newCase);
        }
        insert newCases;

        List newItems = new List();
        for(Integer i_ok = 0; i_ok < 300; i_ok ++){
        Equipment_Maintenance_Item__c i1 = buildItem(newCases[i_ok].Id, equipment.Id);
        newItems.add(i1);
        }
        insert newItems;

        newCases = new List();
        for(Integer i_fail = 0; i_fail < 300; i_fail ++){
        Case newCase = buildCase(vehicle.Id,'Electrical','DummyFAIL_'+i_fail);
        newCases.add(newCase);
        }
        insert newCases;

        newItems = new List();
        for(Integer i_fail = 0; i_fail < 300; i_fail ++){
        Equipment_Maintenance_Item__c i2 = buildItem(newCases[i_fail].Id, equipment.Id);
        newItems.add(i2);
        }
        insert newItems;
        }

        @isTest
        public static void testPositive(){
        Test.startTest();
        List caseToUpdate = new List();
        for(Case newCase : [SELECT Id, Comments, Vehicle__c, Status FROM Case WHERE Subject LIKE ‘DummyOK%’]){
        newCase.Comments = ‘New comment!’;
        caseToUpdate.add(newCase);
        }
        update caseToUpdate;
        System.debug(‘*** Updated cases: ‘+caseToUpdate.size());

        Integer numberAllCases = (Integer) [SELECT COUNT(Id) conteggio FROM Case WHERE Date_Reported__c = TODAY][0].get(‘conteggio’);
        System.debug(‘*** Total cases (expected 900): ‘+numberAllCases);
        System.assert(numberAllCases==900);
        Test.stopTest();
        }

        @isTest
        public static void testNegative(){
        Test.startTest();
        List caseToUpdate = new List();
        for(Case newCase : [SELECT Id, Comments, Vehicle__c, Status FROM Case WHERE Subject LIKE ‘DummyFAIL%’]){
        newCase.Comments = ‘New comment!’;
        caseToUpdate.add(newCase);
        }
        update caseToUpdate;
        System.debug(‘*** Updated cases: ‘+caseToUpdate.size());

        Integer numberAllCases = (Integer) [SELECT COUNT(Id) conteggio FROM Case WHERE Date_Reported__c = TODAY][0].get(‘conteggio’);
        System.debug(‘*** Total cases (expected 600): ‘+numberAllCases);
        System.assert(numberAllCases==600);
        Test.stopTest();
        }

        }

        Reply
      • Thank you for this solution! One question, how does the map newCases get updated with the new Case IDs following the insert tmpCases? Is that just automatically done behind the scenes? For the most part everything else is pretty straightforward and this helped me get my 500 points.

        Reply
    • Hey harsh. Apologies for the codes have changed. As bejng the solo running admin to this page i might not be able to update the solutions on short notice. I had posted these at the time i completed them. And i aint plan to do those again anytime sooner as well.

      Do lemme know if you find solutions codes that work well for it. Paste it below to help someone else looking. Thanks again buddy

      Reply
  5. I am getting invalid type schema: for work_part__c, can you help me how to resolve this on, it doesn’t seems typo error, but i cant find any field of such type also.
    please help.

    Reply
  6. This code works perfectly fine for Challenge 1. Maybe not optimized!

    public with sharing class MaintenanceRequestHelper {

    public static void updateWorkOrders(List caseList) {
    List newCaseList = new List();
    List emiList = new List();
    Set caseIdSet = new Set();

    Map oldNewCaseMap = new Map();
    List emiListToNewCase = new List();
    List emiListToBeUpdated = new List();

    for(case c:caseList){
    caseIdSet.add(c.Id);
    }

    emiList = [Select id,name,Maintenance_Request__c,Equipment__r.Maintenance_Cycle__c from Equipment_Maintenance_Item__c where Maintenance_Request__c IN: caseIdSet];

    Map leastValueMap = new Map();
    for(Equipment_Maintenance_Item__c emi : emiList){
    if(!leastValueMap.containsKey(emi.Maintenance_Request__c)){
    leastValueMap.put(emi.Maintenance_Request__c,emi);
    }
    else if(leastValueMap.containsKey(emi.Maintenance_Request__c) && emi.Equipment__r.Maintenance_Cycle__c < leastValueMap.get(emi.Maintenance_Request__c).Equipment__r.Maintenance_Cycle__c){
    leastValueMap.put(emi.Maintenance_Request__c,emi);
    }
    }
    system.debug('leastValueMap '+leastValueMap);

    for(Case c : caseList){
    if(c.Type == 'Repair' || c.Type == 'Routine Maintenance'){
    Date todayDate = System.today();
    Integer numberOfDays = Integer.valueOf(leastValueMap.get(c.Id).Equipment__r.Maintenance_Cycle__c);
    Case newCase = new Case();
    newCase.Origin = 'Phone';
    newCase.Type = 'Routine Maintenance';
    newCase.Vehicle__c = c.Vehicle__c;
    newCase.Equipment__c = leastValueMap.get(c.Id).Equipment__c;
    newCase.Subject = 'Test Subject';
    newCase.Date_Reported__c = System.today();
    newCase.Date_Due__c = todayDate.addDays(numberOfDays);
    newCaseList.add(newCase);
    oldNewCaseMap.put(c.Id,newCase);
    }
    }
    system.debug('newCaseList '+newCaseList);
    insert newCaseList;

    emiListToNewCase = [Select id,name,Maintenance_Request__c,Equipment__r.Maintenance_Cycle__c from Equipment_Maintenance_Item__c where Maintenance_Request__c IN: oldNewCaseMap.keySet()];

    for(Equipment_Maintenance_Item__c emis : emiListToNewCase){
    Equipment_Maintenance_Item__c e = new Equipment_Maintenance_Item__c();
    e.Equipment__c = emis.Equipment__c;
    e.Maintenance_Request__c = oldNewCaseMap.get(emis.Maintenance_Request__c).Id;
    emiListToBeUpdated.add(e);
    }
    insert emiListToBeUpdated;
    }
    }

    Reply
  7. Hi,

    I am stuck in challenge 6.
    for this code:

    @isTest
    private class WarehouseSyncScheduleTest {
    public static String CRON_EXP = ‘0 0 0 15 3 ? 2022′;

    static testmethod void testjob(){
    MaintenanceRequestTest.CreateData( 5,2,2,’Repair’);
    Test.startTest();
    Test.setMock(HttpCalloutMock.class, new WarehouseCalloutServiceMock());
    String joBID= System.schedule(‘TestScheduleJob’, CRON_EXP, new WarehouseSyncSchedule());
    // List caselist = [Select count(id) from case where case]
    Test.stopTest();
    }
    }

    I am getting ‘Variable does not exist: MaintenanceRequestTest’ error.

    Why it is?

    Please help

    Reply
      • I have Class name MaintenanceRequestHelper and i am adding it but still it not accepting this getting below error.

        Method does not exist or incorrect signature: void CreateData(Integer, Integer, Integer, String) from the type MaintenanceRequestHelper

        Reply
      • I have Class name MaintenanceRequestHelper and i am adding it but still it not accepting this getting below error.

        Method does not exist or incorrect signature: void CreateData(Integer, Integer, Integer, String) from the type MaintenanceRequestHelper

        Reply
  8. Please help me to solve Step 5 :

    Test callout logic
    Build tests for your callout using the included class for the callout mock (WarehouseCalloutServiceMock) and callout test class (WarehouseCalloutServiceTest) in the package. You must have 100% test coverage to pass this challenge and assert values to prove that your logic is working as expected.

    I have tried so many versions of code

    Reply
  9. Challenge Not yet complete… here’s what’s wrong:
    The WarehouseSyncSchedule apex class does not appear to be queuing a job for the WarehouseCalloutService class.

    I have followed all your steps correctly, But I’m still having this error every single time in 3rd challenge.
    Can you please help me out

    Reply
  10. i have already used Queueable interface for WarehouseCalloutService class now i m stuck on step 5 with Test class WarehouseCalloutServiceTest , can you please help me with Test class code ,underlying is the Queueable interface code of WarehouseCalloutService class

    public with sharing class WarehouseCalloutService implements queueable, Database.AllowsCallouts {
    private static final String WAREHOUSE_URL = ‘https://th-superbadge-apex.herokuapp.com/equipment’;

    public void execute(QueueableContext context){
    Http http = new Http();
    HttpRequest request = new HttpRequest();
    request.setEndpoint(WAREHOUSE_URL);
    request.setMethod(‘GET’);
    HttpResponse response = http.send(request);
    if(response.getStatusCode() == 200)
    {
    List externalProducts = (List) JSON.deserializeUntyped(response.getBody());
    List newProducts = new List();

    for(Object p : externalProducts)
    {
    Map productMap = (Map) p;
    Product2 pr = new Product2();
    pr.Replacement_Part__c = (Boolean)productMap.get(‘replacement’);
    pr.Cost__c = (Integer)productMap.get(‘cost’);
    pr.Current_Inventory__c = (Integer)productMap.get(‘quantity’);
    pr.Lifespan_Months__c = (Integer)productMap.get(‘lifespan’) ;
    pr.Maintenance_Cycle__c = (Integer)productMap.get(‘maintenanceperiod’);
    pr.Warehouse_SKU__c = (String)productMap.get(‘sku’);
    pr.ProductCode = (String)productMap.get(‘_id’);
    pr.Name = (String)productMap.get(‘name’);
    newProducts.add(pr);
    }
    if(newProducts.size() >0)
    {
    upsert newProducts;
    }
    }
    }
    }

    Reply
  11. Hi,
    i’m geting error,
    Challenge Not yet complete… here’s what’s wrong:
    We could not find the class ‘MaintenanceRequestHelperTest’ using assertions in the unit tests.

    Reply
  12. for Challenge #2 please run “System.enqueueJob(new WarehouseCalloutService());” in Anonymous window, this will work for sure

    Reply
  13. Can someone please share the working code for 4th (this) challenge…. Hard times…

    Code I used till now :

    Challenge 1 : Automate record creation
    trigger MaintenanceRequest on Case (before update, after update, before insert, after insert) {
    // ToDo: Call MaintenanceRequestHelper.updateWorkOrders’
    if(Trigger.isBefore){
    if(Trigger.isInsert){
    MaintenanceRequestHelper.updateNewMaintenanceRequest(Trigger.new);
    }
    }

    if(Trigger.isAfter){
    if(Trigger.isInsert){
    MaintenanceRequestHelper.createNewEquipmentMaintenanceItem(Trigger.newMap);
    //MaintenanceRequestHelper.createNewEquipmentMaintenanceItemList(Trigger.newMap);
    }
    if(Trigger.isUpdate){
    MaintenanceRequestHelper.createNewMaintenanceRequest(Trigger.oldMap,Trigger.newMap);
    }
    }
    }

    public with sharing class MaintenanceRequestHelper {

    //public static void updateWorkOrders() {
    // TODO: Complete the method to update workorders

    //}

    public static void createNewMaintenanceRequest(Map oldMap, Map newMap){
    List newMRRecordList = new List();
    for(Case MRRecord: newMap.values()){
    if(MRRecord.Status!= oldMap.get(MRRecord.ID).Status && MRRecord.Status == ‘Closed’ && (MRRecord.Type==’Repair’ || MRRecord.Type==’Routine Maintenance’)){
    Case newMRRecord = new Case();
    newMRRecord.Vehicle__c = MRRecord.Vehicle__c;
    newMRRecord.Type=’Routine Maintenance’;
    newMRRecord.Subject=’Routine CheckUp ‘+ date.today();
    newMRRecord.Date_Reported__c=date.today();
    newMRRecord.Date_Due__c=date.today();
    newMRRecordList.add(newMRRecord);
    }
    }
    if(newMRRecordList.size()>0){
    insert newMRRecordList;
    }
    }

    public static void updateNewMaintenanceRequest(List newList){
    List newRoutineMaintenanceVehicleRecordIDList = new List();
    for(Case MRRecord: newList){
    if(MRRecord.Type==’Routine Maintenance’){
    newRoutineMaintenanceVehicleRecordIDList.add(MRRecord.Vehicle__c);
    }
    }
    List newEMIRecordList = new List();
    List EMIList = new List([SELECT Maintenance_Request__c,Maintenance_Request__r.Vehicle__c,Equipment__c, Equipment__r.Maintenance_Cycle__c,Quantity__c FROM Equipment_Maintenance_Item__c WHERE Maintenance_Request__r.Vehicle__c IN: newRoutineMaintenanceVehicleRecordIDList]);
    for(Case MRRecord: newList){
    Decimal maintenanceCycle = 0;
    for(Equipment_Maintenance_Item__c EMIRecord: EMIList){
    if(MRRecord.Vehicle__c==EMIRecord.Maintenance_Request__r.Vehicle__c){
    if(maintenanceCycle==0){
    maintenanceCycle=EMIRecord.Equipment__r.Maintenance_Cycle__c;
    }
    else if(maintenanceCycle > EMIRecord.Equipment__r.Maintenance_Cycle__c){
    maintenanceCycle=EMIRecord.Equipment__r.Maintenance_Cycle__c;
    }
    }
    }
    if(maintenanceCycle>0)
    MRRecord.Date_Due__c=MRRecord.Date_Due__c + integer.valueOf(maintenanceCycle);
    }
    }

    public static void createNewEquipmentMaintenanceItem(Map newMap){
    List newRoutineMaintenanceVehicleRecordIDList = new List();
    for(Case MRRecord: newMap.values()){
    if(MRRecord.Type==’Routine Maintenance’){
    if(!newRoutineMaintenanceVehicleRecordIDList.contains(MRRecord.Vehicle__c))
    newRoutineMaintenanceVehicleRecordIDList.add(MRRecord.Vehicle__c);
    }
    }
    system.debug(‘newRoutineMaintenanceVehicleRecordIDList ‘+newRoutineMaintenanceVehicleRecordIDList);
    List newEMIRecordList = new List();
    List EMIList = new List([SELECT Maintenance_Request__c,Maintenance_Request__r.Vehicle__c,Equipment__c, Equipment__r.Maintenance_Cycle__c,Quantity__c FROM Equipment_Maintenance_Item__c WHERE Maintenance_Request__r.Vehicle__c IN: newRoutineMaintenanceVehicleRecordIDList]);
    system.debug(‘EMIList ‘+EMIList);
    Map<ID,List> vehicleToEquipmentMap = new Map<ID,List>();
    for(Case MRRecord: newMap.values()){
    for(Equipment_Maintenance_Item__c EMIRecord: EMIList){
    if(MRRecord.Vehicle__c==EMIRecord.Maintenance_Request__r.Vehicle__c){
    if(vehicleToEquipmentMap.get(MRRecord.Vehicle__c)!=null){
    List EquipmentIDListUpdate = vehicleToEquipmentMap.get(MRRecord.Vehicle__c);
    if(!EquipmentIDListUpdate.contains(EMIRecord.Equipment__c)){
    EquipmentIDListUpdate.add(EMIRecord.Equipment__c);
    vehicleToEquipmentMap.put(MRRecord.Vehicle__c,EquipmentIDListUpdate);
    Equipment_Maintenance_Item__c newEMIRecord = new Equipment_Maintenance_Item__c();
    newEMIRecord.Quantity__c=EMIRecord.Quantity__c;
    newEMIRecord.Equipment__c=EMIRecord.Equipment__c;
    newEMIRecord.Maintenance_Request__c=MRRecord.ID;
    newEMIRecordList.add(newEMIRecord);
    }
    }
    else{
    List EquipmentIDListUpdate = new List();
    EquipmentIDListUpdate.add(EMIRecord.Equipment__c);
    vehicleToEquipmentMap.put(MRRecord.Vehicle__c,EquipmentIDListUpdate);
    Equipment_Maintenance_Item__c newEMIRecord = new Equipment_Maintenance_Item__c();
    newEMIRecord.Quantity__c=EMIRecord.Quantity__c;
    newEMIRecord.Equipment__c=EMIRecord.Equipment__c;
    newEMIRecord.Maintenance_Request__c=MRRecord.ID;
    newEMIRecordList.add(newEMIRecord);
    }
    }
    }
    }
    if(newEMIRecordList.size()>0){
    system.debug(‘newEMIRecordList.size() ‘+newEMIRecordList.size());
    insert newEMIRecordList;
    }
    }
    }

    Challenge 2 : Synchronize Salesforce data with an external system
    public with sharing class WarehouseCalloutService implements queueable, Database.AllowsCallouts {

    private static final String WAREHOUSE_URL = ‘https://th-superbadge-apex.herokuapp.com/equipment&#8217;;

    public void execute(QueueableContext context){
    Http http = new Http();
    HttpRequest request = new HttpRequest();
    request.setEndpoint(WAREHOUSE_URL);
    request.setMethod(‘GET’);
    HttpResponse response = http.send(request);
    if(response.getStatusCode() == 200)
    {
    List externalProducts = (List) JSON.deserializeUntyped(response.getBody());
    List newProducts = new List();

    for(Object p : externalProducts)
    {
    Map productMap = (Map) p;
    Product2 pr = new Product2();
    pr.Replacement_Part__c = (Boolean)productMap.get(‘replacement’);
    pr.Cost__c = (Integer)productMap.get(‘cost’);
    pr.Current_Inventory__c = (Integer)productMap.get(‘quantity’);
    pr.Lifespan_Months__c = (Integer)productMap.get(‘lifespan’) ;
    pr.Maintenance_Cycle__c = (Integer)productMap.get(‘maintenanceperiod’);
    pr.Warehouse_SKU__c = (String)productMap.get(‘sku’);
    pr.ProductCode = (String)productMap.get(‘_id’);
    pr.Name = (String)productMap.get(‘name’);
    newProducts.add(pr);
    }
    if(newProducts.size() >0)
    {
    upsert newProducts;
    }
    }
    }
    }

    Challenge 3 : Schedule synchronization

    global class WarehouseSyncSchedule implements Schedulable {

    // implement scheduled code here

    global void execute(SchedulableContext ctx) {
    // Sync with Warehouse
    System.enqueueJob(New WarehouseCalloutService());
    }
    }

    Challenge 4 : !!! NEED HELP!!!

    Reply
    • hey Gaurav, this one works for me:

      @isTest
      private class MaintenanceRequestHelperTest {

      @testSetup
      static void allTheDataForThisTestClass() {

      Account acc = new Account();
      acc.Name = ‘test’;
      insert acc;

      Contact contact = new Contact();
      contact.FirstName = ‘test’;
      contact.LastName = ‘last’;
      contact.Email = ‘test@test.com’;
      contact.AccountId = acc.Id;
      insert contact;

      Vehicle__c vehicle = new Vehicle__c();
      vehicle.Name = ‘car’;
      insert vehicle;

      Product2 product = new Product2();
      product.Name = ‘test’;
      product.isActive = true;
      product.Maintenance_Cycle__c = 2;
      product.Replacement_Part__c = true;
      insert product;
      }

      @isTest static void test_triggerMaintenanceRequestHelperTest() {

      Profile p = [SELECT Id FROM Profile WHERE Name=’Standard User’];
      User u = new User(Alias = ‘stdtest’, Email=’stdtest@testorg.com’,
      EmailEncodingKey=’UTF-8′, LastName=’Testing’, LanguageLocaleKey=’en_US’,
      LocaleSidKey=’en_US’, ProfileId = p.Id,
      TimeZoneSidKey=’America/Los_Angeles’, UserName=’stdtest@testorg.com’);

      System.runAs(u) {

      List caseList = new List();
      List secondList = new List();

      Account acc = [SELECT Id, Name FROM Account WHERE Name = ‘test’ LIMIT 1];
      Contact contact = [SELECT Id, FirstName, LastName,Email,AccountId FROM Contact WHERE Email = ‘test@test.com’ LIMIT 1];
      Vehicle__c vehicle = [SELECT Id, Name FROM Vehicle__c WHERE Name = ‘car’ LIMIT 1];
      Product2 product = [SELECT Id, Name, isActive, Maintenance_Cycle__c, Replacement_Part__c FROM Product2 WHERE Name = ‘test’ LIMIT 1];

      Test.startTest();

      for(Integer i=1;i<=1000;i++){
      Case maintenanceNew = new Case();
      maintenanceNew.Subject = 'Other';
      maintenanceNew.Vehicle__c = vehicle.Id;
      maintenanceNew.Product__c = product.Id;
      maintenanceNew.ContactId = contact.Id;
      maintenanceNew.AccountId = acc.Id;
      maintenanceNew.Type = 'Other';
      maintenanceNew.Status = 'New';
      maintenanceNew.ProductId = product.Id;
      maintenanceNew.Date_Reported__c = Date.today();
      maintenanceNew.Date_Due__c = Date.today();

      caseList.add(maintenanceNew);
      }

      insert caseList;

      System.assertEquals(1000,caseList.size());

      for(Case cas:caseList){
      cas.Type = 'Repair';
      cas.Status = 'Closed';
      secondList.add(cas);
      }

      update secondList;
      List createdCases = [Select Id from Case where Type = ‘Routine Maintenance’];
      System.assertEquals(1000,createdCases.size());

      Test.stopTest();

      }

      }
      }

      Reply
    • @isTest
      private class MaintenanceRequestHelperTest {

      @testSetup
      static void allTheDataForThisTestClass() {

      Account acc = new Account();
      acc.Name = ‘test’;
      insert acc;

      Contact contact = new Contact();
      contact.FirstName = ‘test’;
      contact.LastName = ‘last’;
      contact.Email = ‘test@test.com’;
      contact.AccountId = acc.Id;
      insert contact;

      Vehicle__c vehicle = new Vehicle__c();
      vehicle.Name = ‘car’;
      insert vehicle;

      Product2 product = new Product2();
      product.Name = ‘test’;
      product.isActive = true;
      product.Maintenance_Cycle__c = 2;
      product.Replacement_Part__c = true;
      insert product;
      }

      @isTest static void test_triggerMaintenanceRequestHelperTest() {

      Profile p = [SELECT Id FROM Profile WHERE Name=’Standard User’];
      User u = new User(Alias = ‘stdtest’, Email=’stdtest@testorg.com’,
      EmailEncodingKey=’UTF-8′, LastName=’Testing’, LanguageLocaleKey=’en_US’,
      LocaleSidKey=’en_US’, ProfileId = p.Id,
      TimeZoneSidKey=’America/Los_Angeles’, UserName=’stdtest@testorg.com’);

      System.runAs(u) {

      List caseList = new List();
      List secondList = new List();

      Account acc = [SELECT Id, Name FROM Account WHERE Name = ‘test’ LIMIT 1];
      Contact contact = [SELECT Id, FirstName, LastName,Email,AccountId FROM Contact WHERE Email = ‘test@test.com’ LIMIT 1];
      Vehicle__c vehicle = [SELECT Id, Name FROM Vehicle__c WHERE Name = ‘car’ LIMIT 1];
      Product2 product = [SELECT Id, Name, isActive, Maintenance_Cycle__c, Replacement_Part__c FROM Product2 WHERE Name = ‘test’ LIMIT 1];

      Test.startTest();

      for(Integer i=1;i<=1000;i++){
      Case maintenanceNew = new Case();
      maintenanceNew.Subject = 'Other';
      maintenanceNew.Vehicle__c = vehicle.Id;
      maintenanceNew.Product__c = product.Id;
      maintenanceNew.ContactId = contact.Id;
      maintenanceNew.AccountId = acc.Id;
      maintenanceNew.Type = 'Other';
      maintenanceNew.Status = 'New';
      maintenanceNew.ProductId = product.Id;
      maintenanceNew.Date_Reported__c = Date.today();
      maintenanceNew.Date_Due__c = Date.today();

      caseList.add(maintenanceNew);
      }

      insert caseList;

      System.assertEquals(1000,caseList.size());

      for(Case cas:caseList){
      cas.Type = 'Repair';
      cas.Status = 'Closed';
      secondList.add(cas);
      }

      update secondList;
      List createdCases = [Select Id from Case where Type = ‘Routine Maintenance’];
      System.assertEquals(1000,createdCases.size());

      Test.stopTest();

      }

      }
      }

      Reply
  14. Challenge Not yet complete … Here what’s wrong:
    Closing a Maintenance Request of type ‘Routine Maintenance ‘did not create of a new . Maintenance Request to the same vehicle . ( Automate record creation )

    I face this error what can I do please Help me

    Reply
  15. hey all, this one works for me

    @isTest
    private class MaintenanceRequestHelperTest {

    @testSetup
    static void allTheDataForThisTestClass() {

    Account acc = new Account();
    acc.Name = ‘test’;
    insert acc;

    Contact contact = new Contact();
    contact.FirstName = ‘test’;
    contact.LastName = ‘last’;
    contact.Email = ‘test@test.com’;
    contact.AccountId = acc.Id;
    insert contact;

    Vehicle__c vehicle = new Vehicle__c();
    vehicle.Name = ‘car’;
    insert vehicle;

    Product2 product = new Product2();
    product.Name = ‘test’;
    product.isActive = true;
    product.Maintenance_Cycle__c = 2;
    product.Replacement_Part__c = true;
    insert product;
    }

    @isTest static void test_triggerMaintenanceRequestHelperTest() {

    Profile p = [SELECT Id FROM Profile WHERE Name=’Standard User’];
    User u = new User(Alias = ‘stdtest’, Email=’stdtest@testorg.com’,
    EmailEncodingKey=’UTF-8′, LastName=’Testing’, LanguageLocaleKey=’en_US’,
    LocaleSidKey=’en_US’, ProfileId = p.Id,
    TimeZoneSidKey=’America/Los_Angeles’, UserName=’stdtest@testorg.com’);

    System.runAs(u) {

    List caseList = new List();
    List secondList = new List();

    Account acc = [SELECT Id, Name FROM Account WHERE Name = ‘test’ LIMIT 1];
    Contact contact = [SELECT Id, FirstName, LastName,Email,AccountId FROM Contact WHERE Email = ‘test@test.com’ LIMIT 1];
    Vehicle__c vehicle = [SELECT Id, Name FROM Vehicle__c WHERE Name = ‘car’ LIMIT 1];
    Product2 product = [SELECT Id, Name, isActive, Maintenance_Cycle__c, Replacement_Part__c FROM Product2 WHERE Name = ‘test’ LIMIT 1];

    Test.startTest();

    for(Integer i=1;i<=1000;i++){
    Case maintenanceNew = new Case();
    maintenanceNew.Subject = 'Other';
    maintenanceNew.Vehicle__c = vehicle.Id;
    maintenanceNew.Product__c = product.Id;
    maintenanceNew.ContactId = contact.Id;
    maintenanceNew.AccountId = acc.Id;
    maintenanceNew.Type = 'Other';
    maintenanceNew.Status = 'New';
    maintenanceNew.ProductId = product.Id;
    maintenanceNew.Date_Reported__c = Date.today();
    maintenanceNew.Date_Due__c = Date.today();

    caseList.add(maintenanceNew);
    }

    insert caseList;

    System.assertEquals(1000,caseList.size());

    for(Case cas:caseList){
    cas.Type = 'Repair';
    cas.Status = 'Closed';
    secondList.add(cas);
    }

    update secondList;
    List createdCases = [Select Id from Case where Type = ‘Routine Maintenance’];
    System.assertEquals(1000,createdCases.size());

    Test.stopTest();

    }

    }
    }

    Reply
  16. Challenge 4: both negative and bulk run successfully but not positive test case. Please help!

    @istest
    public with sharing class MaintenanceRequestHelperTest {

    private static final string STATUS_NEW = ‘New’;
    private static final string WORKING = ‘Working’;
    private static final string CLOSED = ‘Closed’;
    private static final string REPAIR = ‘Repair’;
    private static final string REQUEST_ORIGIN = ‘Web’;
    private static final string REQUEST_TYPE = ‘Routine Maintenance’;
    private static final string REQUEST_SUBJECT = ‘Testing subject’;

    PRIVATE STATIC Vehicle__c createVehicle(){
    Vehicle__c Vehicle = new Vehicle__C(name = ‘SuperTruck’);
    return Vehicle;
    }

    PRIVATE STATIC Product2 createEq(){
    product2 equipment = new product2(name = ‘SuperEquipment’,
    lifespan_months__C = 10,
    maintenance_cycle__C = 10,
    replacement_part__c = true);
    return equipment;
    }

    PRIVATE STATIC Case createMaintenanceRequest(id vehicleId, id equipmentId){
    case cs = new case(Type=REPAIR,
    Status=STATUS_NEW,
    Origin=REQUEST_ORIGIN,
    Subject=REQUEST_SUBJECT,
    ProductId=equipmentId,
    Vehicle__c=vehicleId);
    return cs;
    }

    PRIVATE STATIC Equipment_Maintenance_Item__c createWorkPart(id equipmentId,id requestId){
    Equipment_Maintenance_Item__c wp = new Equipment_Maintenance_Item__c(Equipment__c = equipmentId,
    Maintenance_Request__c = requestId);
    return wp;
    }

    @istest
    private static void testMaintenanceRequestPositive(){

    Vehicle__c vehicle = createVehicle();
    insert vehicle;
    id vehicleId = vehicle.Id;

    Product2 equipment = createEq();
    insert equipment;
    id equipmentId = equipment.Id;

    System.debug(vehicleId+’ ‘+equipmentId);

    case somethingToUpdate = createMaintenanceRequest(vehicleId,equipmentId);
    insert somethingToUpdate;

    Equipment_Maintenance_Item__c workP = createWorkPart(equipmentId,somethingToUpdate.id);
    insert workP;

    test.startTest();
    somethingToUpdate.status = CLOSED;
    update somethingToUpdate;

    test.stopTest();

    Case newReq = [Select id, subject, type, Date_Reported__c, Vehicle__c, Date_Due__c
    from Case
    where status = :STATUS_NEW];

    Equipment_Maintenance_Item__c workPart = [select id
    from Equipment_Maintenance_Item__c
    where Maintenance_Request__c = :newReq.Id];

    system.assert(workPart != null);
    system.assert(newReq.Subject != null);
    system.assertEquals(newReq.Type, REQUEST_TYPE);
    SYSTEM.assertEquals(newReq.ProductId, equipmentId);
    SYSTEM.assertEquals(newReq.Vehicle__c, vehicleId);
    SYSTEM.assertEquals(newReq.Date_Reported__c, system.today());

    }

    @istest
    private static void testMaintenanceRequestNegative(){
    Vehicle__C vehicle = createVehicle();
    insert vehicle;
    id vehicleId = vehicle.Id;

    product2 equipment = createEq();
    insert equipment;
    id equipmentId = equipment.Id;

    case emptyReq = createMaintenanceRequest(vehicleId,equipmentId);
    insert emptyReq;

    Equipment_Maintenance_Item__c workP = createWorkPart(equipmentId, emptyReq.Id);
    insert workP;

    test.startTest();
    emptyReq.Status = WORKING;
    update emptyReq;
    test.stopTest();

    list allRequest = [select id
    from case];

    Equipment_Maintenance_Item__c workPart = [select id
    from Equipment_Maintenance_Item__c
    where Maintenance_Request__c = :emptyReq.Id];

    system.assert(workPart != null);
    system.assert(allRequest.size() == 1);
    }

    @istest
    private static void testMaintenanceRequestBulk(){
    list vehicleList = new list();
    list equipmentList = new list();
    list workPartList = new list();
    list requestList = new list();
    list oldRequestIds = new list();

    for(integer i = 0; i < 300; i++){
    vehicleList.add(createVehicle());
    equipmentList.add(createEq());
    }
    insert vehicleList;
    insert equipmentList;

    for(integer i = 0; i < 300; i++){
    requestList.add(createMaintenanceRequest(vehicleList.get(i).id, equipmentList.get(i).id));
    }
    insert requestList;

    for(integer i = 0; i < 300; i++){
    workPartList.add(createWorkPart(equipmentList.get(i).id, requestList.get(i).id));
    }
    insert workPartList;

    test.startTest();
    for(case req : requestList){
    req.Status = CLOSED;
    oldRequestIds.add(req.Id);
    }
    update requestList;
    test.stopTest();

    list allRequests = [select id
    from case
    where status =: STATUS_NEW];

    list workParts = [select id
    from Equipment_Maintenance_Item__c
    where Maintenance_Request__c in: oldRequestIds];

    system.assert(allRequests.size() == 300);
    }
    }

    Reply
  17. You also need to Insert Equipment Maintenance item after inserting the case for challenge 1.
    Below is the code which needs to be added on.
    …..
    }
    }
    insert newCases;
    List itemInsert = new List();
    List item = new List();
    Map caseKeys =new Map(caseList);
    item=[SELECT ID,Maintenance_Request__r.ID,Maintenance_Request__r.CaseNumber,Maintenance_Request__c,Equipment__r.ID,Equipment__c,Equipment__r.Name,Equipment__r.Maintenance_cycle__c
    from Equipment_Maintenance_Item__c where Maintenance_Request__r.ID in :caseKeys.keySet()];
    for(case nc : newCases)
    {
    for(Equipment_Maintenance_Item__c i : item)
    { if(i.Maintenance_Request__c == nc.ParentId)
    {
    Equipment_Maintenance_Item__c e = new Equipment_Maintenance_Item__c();
    //e.Maintenance_Request__r.ID = nc.ID;
    e.Maintenance_Request__c=nc.ID;
    //e.Equipment__r.ID =i.Equipment__r.ID;
    e.Equipment__c=i.Equipment__r.ID;
    itemInsert.add(e);
    }

    }
    }
    insert itemInsert;

    Reply
  18. It removed the angle bracket considering it html tag insert wherever necessary of that specific object.
    }
    }
    insert newCases;
    List<> itemInsert = new List();
    List> item = new List<();
    Map> caseKeys =new Map(caseList);
    item=[SELECT ID,Maintenance_Request__r.ID,Maintenance_Request__r.CaseNumber,Maintenance_Request__c,Equipment__r.ID,Equipment__c,Equipment__r.Name,Equipment__r.Maintenance_cycle__c
    from Equipment_Maintenance_Item__c where Maintenance_Request__r.ID in :caseKeys.keySet()];
    for(case nc : newCases)
    {
    for(Equipment_Maintenance_Item__c i : item)
    { if(i.Maintenance_Request__c == nc.ParentId)
    {
    Equipment_Maintenance_Item__c e = new Equipment_Maintenance_Item__c();
    //e.Maintenance_Request__r.ID = nc.ID;
    e.Maintenance_Request__c=nc.ID;
    //e.Equipment__r.ID =i.Equipment__r.ID;
    e.Equipment__c=i.Equipment__r.ID;
    itemInsert.add(e);
    }

    }
    }
    insert itemInsert;

    Reply
  19. Challenge Not yet complete… here’s what’s wrong:
    Closing a Maintenance Request of type ‘Routine Maintenance’ did not create of a new Maintenance Request related to the same Vehicle.
    2
    Automate record creation
    Install the unlocked package and configure the development org.

    Use the included package content to automatically create a Routine Maintenance request every time a maintenance request of type Repair or Routine Maintenance is updated to Closed. Follow the specifications and naming conventions outlined in the business requirements.

    Reply

Leave a Reply

error: Content is protected !!