0

I have a simple class that just calls the generic HTTPCallOUt method for its test class.

I want it to be able to fail in order to catch all the code. Here is my code:

    Test.startTest(); 
    Test.setMock(HttpCalloutMock.class, new ExampleCalloutMock()); // I want this to be able to 
    fail in order to catch all the code in ClassCall 
    ClassCall.Method(recordId);
    test.stopTest();

Right now it always returns Code 200 and passes the test. I want it to return anything other than code 200.

0

1 Answer 1

3

What I do is dependency inject the desired static code into the mock's constructor

Test.startTest(); 
Test.setMock(HttpCalloutMock.class, new ExampleCalloutMock(400)); // <= inject desired status code  
ClassCall.Method(recordId);
test.stopTest();

The mock callout

public class ExampleCalloutMock implements HttpCalloutMock {
  Integer statusCode;
  ExampleCalloutMock(Integer statusCode) {this.statusCode = statusCode;}

  public HTTPResponse respond(HTTPRequest req) {
    
    
    // Create a fake response
    HttpResponse res = new HttpResponse();
    res.setHeader('Content-Type', 'application/json');
    res.setBody('{"example":"test"}');
    res.setStatusCode(this.statusCode);  // use injected status code as response
    return res;
   }
  }
2
  • Hi @cropredy in your answer do I need to create a new Class with the HTTP response? Commented Jun 8, 2022 at 16:00
  • 1
    see the documentation -- the mock callout class can be a top level class, or, in most cases, can be an inner class inside your test class
    – cropredy
    Commented Jun 8, 2022 at 16:05

Not the answer you're looking for? Browse other questions tagged .