0

I always get an Fail when try to test the negative scenario. How can I fix it? Sorry, I'm just learning.

Callout:

public class MyException extends Exception {}
public class Token{
    public String accessToken{get;set;}    
}

public static String accessTokenBody(){  //our web token (data is in fields)
        Settings__c settings = [SELECT ConsumerKey__c, ClientSecret__c, Username__c, Password__c, SecurityToken__c
                                FROM Settings__c
                                WHERE Name = 'OurSettings'];  
        String consumerKey = settings.ConsumerKey__c;
        String consumerSecret = settings.ClientSecret__c;
        String username = settings.Username__c;
        String password = settings.Password__c + settings.SecurityToken__c;
        String request = 'grant_type=password&client_id=' + consumerKey +'&client_secret=' + consumerSecret +
                         '&username=' + username + '&password='+password;
        return request;
    }

public static String GenerateJSON(Type__c t){
//I will send and post it like a record in another org:
    Map<String, String> fieldMap = new Map<String, String>{
                   'Name' => t.Name,
                   'Desc__c' => t.Type_Description__c};    
    String serialized = JSON.serialize(fieldMap);         
    return serialized;
 }

public static HttpRequest httpRequest(String service){
    String requestBody = accessTokenBody();
    HttpRequest ourRequest = new HttpRequest();
    ourRequest.setBody(requestBody);
    ourRequest.setMethod(service);
    ourRequest.setEndpoint('https://p21.lightning.force.com/services/oauth2/token');
    return ourRequest;
}

public static HttpRequest finalHttpRequest(String token, String method, String endpointUrl){
    HttpRequest finalRequest = new HttpRequest();
    finalRequest.setHeader('Authorization','Bearer ' + token);
    finalRequest.setHeader('Content-Type','application/json');
    finalRequest.setHeader('accept','application/json');
    finalRequest.setMethod(method);
    finalRequest.setEndpoint('https://p21.lightning.force.com/services/oauth2/token' + endpointUrl);
    return finalRequest;
}

public static HttpResponse postCallout(String positionId) {
    Http ourHttp = new Http();
    HttpRequest request = httpRequest('POST');
    HttpResponse response = ourHttp.send(request);      
    Token objAuthenticationInfo = (Token)JSON.deserialize(response.getbody(), Token.class);

    if(objAuthenticationInfo.ACCESS_TOKEN != null){
        Type__c typ = [SELECT Id, Name FROM Type__c WHERE Id =: TypeID];
        HttpRequest finalRequest = finalHttpRequest(objAuthenticationInfo.ACCESS_TOKEN, 'POST', '');
        finalRequest.setBody(GenerateJSON(typ));
        HttpResponse finalResponse = ourHttp.send(finalRequest);
        if(finalResponse.getStatusCode() == 200) {
            System.debug('CREATED:  ' + finalResponse.getBody());
            return finalResponse;
        }else {
            throw new MyException('Not 200');
        }
    }
    throw new MyException('No token');
}

Mock:

@isTest
global class AnimalsHttpCalloutMock implements HttpCalloutMock {
global HTTPResponse respond(HTTPRequest request) {
    HttpResponse response = new HttpResponse();
    response.setHeader('Content-Type', 'application/json');
    String serialized;
    if(request.getEndpoint().contains('services/oauth2/token')) {
      serialized = '{ "accessToken": "FAKE-ACCESS-TOKEN" }';
    } else {
      serialized = '{ }'; // return correct JSON for second callout here
    }
    response.setBody(serialized);
    response.setStatusCode(200);
    return response;
}
}

Test:

@isTest
private class CalloutTest {

@isTest
static void testPostCallout() {              
    Settings__c settings = new Settings__c(Name = 'OurSettings',
                                           ConsumerKey__c = '****',
                                           ClientSecret__c = '*****',
                                           Username__c = '*****',
                                           SecurityToken__c = '****',
                                           Password__c = 'mypassword1');
    insert settings;

    String consumerKey = settings.ConsumerKey__c;
    String consumerSecret = settings.ClientSecret__c;
    String username = settings.Username__c;
    String password = settings.Password__c + settings.SecurityToken__c;
    String request = 'grant_type=password&client_id=' + consumerKey +'&client_secret=' + consumerSecret +
                     '&username=' + username + '&password='+password;

    Type__c typ = new Type__c(Name = 'ttt');
    insert typ;

    Test.startTest(); 
    Test.setMock(HttpCalloutMock.class, new AnimalsHttpCalloutMock());
//I become here MyError msg, but it's always fail (and I need success):
    HttpResponse response = CalloutClass.postCallout(typ.Id);
    String contentType = response.getHeader('Content-Type');
    System.assert(contentType == 'application/json');
    String actualValue = response.getBody();
    System.debug(response.getBody());
    String expectedValue = '{ }';
    System.assertEquals(actualValue, expectedValue);
    System.assertEquals(200, response.getStatusCode());
    Test.stopTest(); 
}

public class Token{
    public String accessToken{get;set;}    
}
}

Or maybe I need return something else for negative scenario?

  • 2
    Like I said in my prior answer, you will need to modify your mock to return the expected value in order to cover the else branch. – sfdcfox Oct 16 '18 at 14:21
  • Yes, I understand that. But throw new Exception is uncoverable. It's always fail, even when get MyException msg. – MichaelLev19 Oct 16 '18 at 14:46
2

To cover the exception (and not get a failed test), you have to try-catch, just like any other exception:

try {
  HttpResponse response = CalloutJobAdvertisement.postCallout(pos.Id);
  System.assert(false, 'Expected an exception to be thrown.');
} catch(CalloutJobAdvertisement.MyException e) {
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.