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
rexeusrexeus 

Data Integration Specialist- Level 4- Failed Tests of Apex Callouts

Guys-

I am testing an apex class (projectCalloutService). I took a different approach and made some class variables static because to avoid having to pass any parameters to queueable interface ( just to try it out). However, my test methods assertion failed in projectCalloutServiceTest class. I use VScode for my dev work and I tried to debug using Apex replay debugger and found out that my Static Variables of the projectCalloutService class becomes null and I dont understand why. Any help is appreciated and most likely I am making a dumb mistake somewhere.. thanks in advance!
 
public class ProjectCalloutService {
    static Opportunity opportunityObj;
    static Opportunity opp ;
    
    
    @InvocableMethod(label='Post Opportunity To PMS' description='Synchronize Outbound Project Data')  
    public static void PostOpportunityToPMS(List<Id> opportunityIds) {
        Opportunity opp = [SELECT Amount,CloseDate,Id,Name,StageName,Account.Name FROM Opportunity WHERE Id =: opportunityIds.get(0)] ; 
        Opportunity opportunityObj;
        ID newJobId = System.enqueueJob(new QueueablePMSCall());
        System.debug(newJobId);
    }
    
    @Future(callout=true) 
    private static void makeServiceCall( ){
        
        opportunityObj = opp;
        JSONGenerator gen = JSON.createGenerator(true); // DO NOT USE JSON as variable (Case Insensitive)
        gen.writeStartObject();
        gen.writeStringField('opportunityId', opp.Id);
        gen.writeStringField('opportunityName', opp.Name);
        gen.writeStringField('accountName', opp.account.Name);
        gen.writeDateField('closeDate', opp.closeDate);
        gen.writeNumberField('amount', opp.amount);            
        gen.writeEndObject();      
        String jsonReq= gen.getAsString();
        System.debug('jsonReq: ' + jsonReq);
        
        
        
        
        ServiceTokens__c token= ServiceTokens__c.getValues('ProjectServiceToken');
        System.debug('TOKEN is :'+token.Token__c);
        Http http = new Http();
        HttpRequest request = new HttpRequest();
        request.setEndpoint('callout:ProjectService/'+token.Token__c);
        System.debug('ENDPOINT is :'+'callout:ProjectService/'+token.Token__c);
        request.setMethod('POST');
        request.setHeader('Content-Type', 'application/json;charset=UTF-8');
        request.setBody(jsonReq);
        HttpResponse response = http.send(request);
        System.debug('RESPONSE is :'+response);
        
        
        // Parse the JSON response
        if (response.getStatusCode() != 201) {
            System.debug('The status code returned was not expected: ' +
                         response.getStatusCode() + ' ' + response.getStatus());
            opportunityObj.StageName='Resubmit Project';
            upsert opportunityObj;
            
        } else {
            
            System.debug(response.getBody());
            opportunityObj.StageName='Submitted Project';
            upsert opportunityObj;
            
        }
        
        
        
    }
    
    
    
    // Queue 
    class QueueablePMSCall implements Queueable,Database.AllowsCallouts
    {
        
        public void execute(QueueableContext context) {
            
            makeServiceCall();
        }
        
    }
    
    
}
@isTest
private class ProjectCalloutServiceTest {
    
    @TestSetup
    static void makeData(){
        //create the Custom Settings
        ServiceTokens__c servToken = new ServiceTokens__c();
        servToken.Name = 'ProjectServiceToken';
        servToken.Token__c = 'jkhasbdha';
        insert servToken;
        
        Account testAcct = new Account(Name='TestOpAct');
        insert testAcct;
        
        List<Opportunity> oppList = new list<Opportunity>();
        Opportunity testOpp1 = new Opportunity(Name='TestOp1',StageName='Closed Won',Type='New Project',CloseDate=system.today(), AccountId = testAcct.id, Amount=50000);     
        Opportunity testOpp2 = new Opportunity(Name='TestOp2',StageName='Closed Won',Type='New Project',CloseDate=system.today(), AccountId = testAcct.id, Amount=50000);
        System.debug(testOpp1);
        oppList.add(testOpp1);
        oppList.add(testOpp2);
        upsert opplist; 
        System.debug(opplist);
        
        
        
        
        
        System.debug(testOpp1);
        
    }
    
    
    
    @isTest 
    public static void successTest(){    
        
        List<Id> oppIds = new List<Id>(new Map<Id,Opportunity>([SELECT Name,Id FROM Opportunity WHERE Name = 'Testop1']).keySet());
        
        // If an HTTP callout is invoked in test context, the callout is not made. Instead, you receive the mock response that you specify in the respond method implementation in AnimalLocatorMock.
        // Set mock callout class 
        
        Test.startTest();
        Test.setMock(HttpCalloutMock.class, new ProjectCalloutServiceMock()); 
        ProjectCalloutService.PostOpportunityToPMS(oppIds);
        Test.stopTest();
        
        
        Opportunity opp = [SELECT Name, StageName FROM Opportunity where Name='TestOp1'];
        System.assert(opp.StageName=='Submitted Project');
        
        
    }
    
    @isTest 
    public static void failureTest(){
        
        List<Id> oppIds = new List<Id>(new Map<Id,Opportunity>([SELECT Name,Id FROM Opportunity WHERE Name = 'Testop2']).keySet());
        
        Test.startTest();
        Test.setMock(HttpCalloutMock.class, new ProjectCalloutServiceMockFailure()); 
        ProjectCalloutService.PostOpportunityToPMS(oppIds);
        Test.stopTest();
        Opportunity opp = [SELECT Name, StageName FROM Opportunity where Name='TestOp2'];
        System.assert(opp.StageName=='Resubmit Project');
        
        
        
    }
    
    
    
}

 
Raj VakatiRaj Vakati
Use this code 
 
public class ProjectCalloutServiceMockFailure implements HttpCalloutMock {

    public HttpResponse respond(HttpRequest req) {
        HttpResponse resp = new HttpResponse();
        resp.setHeader('Content-Type', 'application/json');
        resp.setStatusCode(400);
        resp.setStatus('Bad Request');
        return resp;
    }
}
 
public class ProjectCalloutServiceMock implements HttpCalloutMock {

    public HttpResponse respond(HttpRequest req) {
        HttpResponse resp = new HttpResponse();
        resp.setHeader('Content-Type', 'application/json');
        resp.setStatusCode(201);
        resp.setStatus('Created');
        return resp;
    }
}
 
@isTest
private class ProjectCalloutServiceTest {

    @TestSetup
    private static void setup() {
        ServiceTokens__c st = new ServiceTokens__c(
                name = ProjectCalloutService.PROJECT_SERVICE_TOKEN_NAME,
                Token__c = 'test-service-token'
        );
        insert st;
    }

    private static testMethod void testFailure() {
        Opportunity opp = createOpportunity();

        Test.startTest();
        Test.setMock(HttpCalloutMock.class, new ProjectCalloutServiceMockFailure());
        ProjectCalloutService.postOpportunityToPMS(new List<Id>{opp.Id});
        Test.stopTest();

        System.assertEquals('Resubmit Project', queryOpportunity(opp.Id).StageName);
    }

    private static testMethod void testSuccess() {
        Opportunity opp = createOpportunity();

        Test.startTest();
        Test.setMock(HttpCalloutMock.class, new ProjectCalloutServiceMock());
        ProjectCalloutService.postOpportunityToPMS(new List<Id>{opp.Id});
        Test.stopTest();

        System.assertEquals('Submitted Project', queryOpportunity(opp.Id).StageName);
    }

    private static Opportunity createOpportunity() {
        Opportunity opp = new Opportunity(
                Name = 'TestOpportunity',
                StageName = 'Closed Won',
                CloseDate = Date.today().addYears(1)
        );
        insert opp;
        return opp;
    }

    private static Opportunity queryOpportunity(Id oppId) {
        return [SELECT StageName FROM Opportunity WHERE Id =: oppId LIMIT 1];
    }
}

 
rexeusrexeus
Thanks but I replaced my code with yours and its still failing with the same error. Could you please share your ProjectCalloutService class code ?
Mayur MehtaMayur Mehta
I am also stuck with this challenge, however i am getting an error 'Methods defined as TestMethod do not support Web service callouts'. I am unable to identify the area of my code where i need to update. Below are my code:

@IsTest
public class ProjectCalloutServiceMock implements HttpCallOutMock{
   //Implement http mock callout here
    public HttpResponse respond(HttpRequest req)
    {
        HttpResponse res = new HttpResponse();
        res.setHeader('Content-Type', 'application/json');
        res.setStatus('OK');
        res.setStatusCode(201);
        return res;
    }
}

@Istest
public class ProjectCalloutServiceMockFailure implements HttpCallOutMock {
   //Implement http mock callout failure here
   public HttpResponse respond(HttpRequest req)
    {
        HttpResponse res = new HttpResponse();
        res.setHeader('Content-Type', 'application/json');
        res.setStatus('Error');
        res.setStatusCode(500);
        return res;
    }
}

@isTest
private class ProjectCalloutServiceTest {
  //Implement mock callout tests here
  @testsetup
  public static void setupdata()
  {
      List<Opportunity> oppsToInsert = new List<Opportunity>();
      
      Account acct = new Account();
      acct.Name='test Account';
      insert acct;
      
      Opportunity opp1 = new Opportunity();
      opp1.Name = 'Opp1';
      opp1.Type='New Customer';
      opp1.AccountId = acct.id;
      opp1.amount=500;
      opp1.CloseDate = date.today();
      opp1.StageName = 'Prospecting';
      oppsToInsert.add(opp1);
      
      Opportunity opp2 = new Opportunity();
      opp2.Name = 'Opp2';
      opp2.Type='New Customer';
      opp2.AccountId = acct.id;
      opp2.amount=2500;
      opp2.CloseDate = date.today().addDays(-3);
      opp2.StageName = 'Prospecting';
      oppsToInsert.add(opp2);
      
      insert oppsToInsert;
      
      ServiceTokens__c st = new ServiceTokens__c();
      st.Name = 'ProjectServiceToken';
      st.Token__c = 'thisistesttoken';
      insert st;
      
  }
    
   @istest
    public static void testSuccessMessage()
    {
        Opportunity oppList = [Select Id from Opportunity where Name='Opp1' limit 1];
        List<Id> oppIds = new List<Id>();
        oppIds.add(oppList.Id);
        Test.setMock(HttpCalloutMock.class, new ProjectCalloutServiceMock());
        test.startTest();
            ProjectCalloutService.postOpportunityToPMS(oppIds);
        test.stopTest();
        oppList = [Select StageName from Opportunity where Name='Opp1' limit 1];
        system.assertEquals('Submitted Project',oppList.StageName);
    }
    
    @istest
    public static void testFailureMessage()
    {
        Opportunity oppList = [Select Id from Opportunity where Name='Opp2' limit 1];
        List<Id> oppIds = new List<Id>();
        oppIds.add(oppList.Id);
        Test.setMock(HttpCalloutMock.class, new ProjectCalloutServiceMockFailure());
        test.startTest();
            ProjectCalloutService.postOpportunityToPMS(oppIds);
        test.stopTest();
        oppList = [Select StageName from Opportunity where Name='Opp2' limit 1];
        system.assertEquals('Resubmit Project',oppList.StageName);
    }
}