+ Start a Discussion
LABBOOLABBOO 

Apex Specialist Superbadge Challenge #6 - Can't get successful run

I'm stuck.  Worked through most of my issues but now every time I run the test on this test class I get a "Methods defined as TestMethod do not support Web service callouts" error.  Can someone help identify what I have incorrect in my test class?  Is there something I have to do to force it to use the Mock instead that I just don't see?

Here's that I have in the test class:
@isTest
public class WarehouseSyncTest {

     @isTest static void testScheduledJob() {
        String CRON_EXP = '0 0 0 15 3 ? 2022';
        Test.startTest();
        String jobid = System.schedule('EquipTest', CRON_EXP, new WarehouseSyncSchedule());
        Test.stopTest();
        CronTrigger ct = [SELECT State FROM CronTrigger WHERE ID = :jobId];
        System.assertEquals('WAITING', String.valueOf(ct.State));
    }
}

Have also tried it with private instead of public on the class - and I get the same error.
Best Answer chosen by LABBOO
LABBOOLABBOO
@Nithesh N, I have both of those and already passed Challenge #5 but it's still failing.  I'm guessing there's something wrong in my WarehouseSyncTest where I'm trying to test the Scheduled job that is not taking advantage of the Mock Class and I don't know how to get it to do so.

But what I did need was the Test.setMock(HttpCalloutMock.class, new WarehouseCalloutServiceMock()); line in my class above (already had the rest)

All Answers

Nithesh NNithesh N

Hey, You can check my Code below as Referrence. 

Methods defined as TestMethod do not support Web service callouts , So we Create a Mock Class (WarehouseCalloutServiceMock in this case) which serves as a fake Webservice to receive our callout from the Test class. 

@isTest
private class WarehouseCalloutServiceTest {
  // implement your mock callout test here
  @isTest
    static void WarehouseEquipmentSync(){
        Test.startTest();
        // Set mock callout class 
        Test.setMock(HttpCalloutMock.class, new WarehouseCalloutServiceMock()); 
        // This causes a fake response to be sent from the class that implements HttpCalloutMock. 
        WarehouseSyncSchedule syncMe = new WarehouseSyncSchedule();
        Datetime dt = Datetime.now().addMinutes(3);
        String CRON_EXP = '0 '+ dt.minute() + ' * ' + dt.day() + ' ' + dt.month() + ' ? ' + dt.year();
        String jobID = System.schedule('Test the Queue Status', CRON_EXP, syncMe);
        CronTrigger cTId = [SELECT State FROM CronTrigger WHERE Id = :jobID];
        System.assertEquals('WAITING', String.valueOf(cTId.State), 'jobID Doesnt Match');
        Test.stopTest();             
        
    }
    
}

WarehouseCalloutServiceMock​ :
@isTest
global class WarehouseCalloutServiceMock implements HttpCalloutMock {
    // implement http mock callout
    global HttpResponse respond(HttpRequest request){
        
        System.assertEquals('https://th-superbadge-apex.herokuapp.com/equipment', request.getEndpoint());
        System.assertEquals('GET', request.getMethod());
        
      // Create a fake response
    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"}]');
        response.setStatusCode(200);
        return response;
    }
}


Please mark this Solution as Best Solution if it solves your Question.

Best,
Nithesh.
LABBOOLABBOO
@Nithesh N, I have both of those and already passed Challenge #5 but it's still failing.  I'm guessing there's something wrong in my WarehouseSyncTest where I'm trying to test the Scheduled job that is not taking advantage of the Mock Class and I don't know how to get it to do so.

But what I did need was the Test.setMock(HttpCalloutMock.class, new WarehouseCalloutServiceMock()); line in my class above (already had the rest)
This was selected as the best answer
Prashant Menon 2Prashant Menon 2
Yes, the above code does get validated and seem correct (logical) - Force the Scheduled to run in Start/Stop and then make it sync process again.
However, did you see any record being fetched from the MockService?

I am not able to see that record being fetched and am unable to understand what I have done wrong here.
 
@isTest //(SeeAllData = True)
private class WarehouseSyncScheduleTest {

    //Dummy CRON expression. below value does not matter
    public static String CRON_EXP = '0 0 1 * 2 ? 2018';
    
    @isTest
    static void testScheduledJob() {
        Integer sCount = 0;
        CronTrigger cTId;
        
        Test.startTest();
        	Test.setMock(HttpCalloutMock.class, new WarehouseCalloutServiceMock());
        	String jobID = System.schedule('Test Scheduler', CRON_EXP, new WarehouseSyncSchedule());
        	
        	sCount = [Select count() From Product2 Where 
                      Replacement_Part__c = True AND 
                      Current_Inventory__c = 100 AND 
                      Name = 'Breaker 25A' AND 
                      Maintenance_Cycle__c = 0 AND 
                      Lifespan_Months__c = 0 AND 
                      Cost__c = 30 AND 
                      Warehouse_SKU__c = '100012'];
        
        	System.assertEquals(0, sCount, 'Record exists before the job has run!');
        	System.Debug('Count of Records inserted = '+sCount); 
        	// Stopping the test will run the job synchronously
        	
            cTId = [SELECT State FROM CronTrigger WHERE Id = :jobID];
            System.Debug(String.valueOf(cTId.State));
        
        Test.stopTest();
        
        cTId = [SELECT State FROM CronTrigger WHERE Id = :jobID];
        System.Debug(String.valueOf(cTId.State));
        
        sCount = [Select count() From Product2 Where 
                  Replacement_Part__c = True AND 
                  Current_Inventory__c = 100 AND 
                  Name = 'Breaker 25A' AND 
                  Maintenance_Cycle__c = 0 AND 
                  Lifespan_Months__c = 0 AND 
                  Cost__c = 30 AND 
                  Warehouse_SKU__c = '100012'];
        
        System.Debug('Count of inserts ='+ [Select count() from Product2 Where ID <> NULL]);
        
        	System.AssertEquals(1,sCount, 'The Inserted test record does not match the intended one.');
        System.Debug('Count of Records inserted = '+sCount);        
        
    }
}

 
Prashant Menon 2Prashant Menon 2
Here, I would have expected the count in the last assert to be 1 as my mock inserts the above mentioned Product2 record.
The SQL count returns 0
Also, the CronTrigger Status for the job is returned as Waiting post the StopTest();

Am I doing something wrong?
Nidhi gupta 150Nidhi gupta 150
@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();
    }

}

the code works.. you can find more solutions at salesforcehandle.com
Bhavishya KumarBhavishya Kumar
Type is not visible: MaintenanceRequestTest 
how to solve this error. Kindly help
Mila MirovicMila Mirovic
Try this link (https://www.automationcodes.com/2022/01/apex-specialist-superbadge-solutions.html). You should just add 1 line:
WarehouseCalloutService.execute(context);

in test method to gain 100% coverage.