Skip to main content

according to the code, everything should be working...

 

  • Add a unit test method called testNegativeMocking to ExternalSearchTests.cls that uses the HTTPMockFactory class to return a 500 response.

 

but : We can’t find the 'HttpMockFactory' being used to return a '500' response in the 'testNegativeMocking' method...

 

public class ExternalSearch {

    public static HttpResponse search() {

        HttpRequest req = new HttpRequest();

        req.setEndpoint('https://api.example.com/search');

 

        req.setMethod('GET');

        

        try {

            Http http = new Http();

            return http.send(req);

        } catch (Exception e) {

          //  System.debug('Exception occurred: ' + e.getMessage());

            return null;

        }

    }

}

 

private class ExternalSearchTests {

 

  // Test method for success scenario

    @isTest

    static void testPositiveMocking() {

        Test.setMock(HttpCalloutMock.class, new HTTPMockFactory());

        

        HttpResponse response = ExternalSearch.search();

        

        System.assertEquals(200, response.getStatusCode());

    }

 

    // Test method for failure scenario

@isTest

static void testNegativeMocking() {

    Test.startTest();

    Test.setMock(HttpCalloutMock.class, new NegativeHTTPMockFactory());

    

    HttpResponse response = ExternalSearch.search(); // This line is likely causing the NullPointerException

    

    System.debug('Response: ' + response); // Add this debug statement to see if response is null

    

    System.assertEquals(500, response.getStatusCode());

    Test.stopTest();

}}

 

@IsTest

public class HTTPMockFactory implements HttpCalloutMock {

  protected Integer code;

  protected String status;

  protected String body;

  protected Map<String, String> responseHeaders;

  public HTTPMockFactory(

    Integer code,

    String status,

    String body,

    Map<String, String> responseHeaders

  ) {

    this.code = code;

    this.status = status;

    this.body = body;

    this.responseHeaders = responseHeaders;

  }

  public HTTPResponse respond(HTTPRequest req) {

    HttpResponse res = new HttpResponse();

    for(String key : this.responseHeaders.keySet()) {

      res.setHeader(key, this.responseHeaders.get(key));

    }

    res.setBody(this.body);

    res.setStatusCode(this.code);

    res.setStatus(this.status);

    return res;

  }

}

1 answer
0/9000