+ Start a Discussion
dhruv aroradhruv arora 

please help me to complete this challenge.help me in writting its test class

public class AnimalLocator { public class Animal { public Integer id; public String name; public String eats; public String says; } public class AnimalResult { public Animal animal; } public static String getAnimalNameById(Integer id) { Http http = new Http(); HttpRequest request = new HttpRequest(); request.setEndpoint('https://th-apex-http-callout.herokuapp.com/animals/' + id); request.setMethod('GET'); HttpResponse response = http.send(request); AnimalResult result = (AnimalResult) JSON.deserialize(response.getBody(), AnimalResult.class); return result.animal.name; } }
Naresh YadavNaresh Yadav
Hi Dhruv

Use the below code.
 
@isTest
public class AnimalLocatorTest{
    @isTest
    private static void unitTest(){
        Test.setMock(HttpCalloutMock.class, new AnimalLocatorMock());
        String response = AnimalLocator.getAnimalNameById(1);
        
    }
}
 
@isTest
global class AnimalLocatorMock implements HttpCalloutMock {
    // Implement this interface method
    global HTTPResponse respond(HTTPRequest request) {
        // Create a fake response
        HttpResponse response = new HttpResponse();
        response.setHeader('Content-Type', 'application/json');
        response.setBody('{"animal":{"id":1,"name":"chicken","eats":"chicken food","says":"cluck cluck"}}');
        response.setStatusCode(200);
        return response; 
    }
}

Mark it solution if it will solve your problem.
Naresh.
Amit Chaudhary 8Amit Chaudhary 8
Please check below post for same issue
1) https://developer.salesforce.com/forums/?id=906F0000000MJXvIAO
2) https://developer.salesforce.com/forums/?id=906F0000000MJiKIAW

Create moke class like below
@isTest
global class AnimalLocatorMock implements HttpCalloutMock {
    global HTTPResponse respond(HTTPRequest request) {
         HttpResponse response = new HttpResponse();
        response.setHeader('Content-Type', 'application/json');
        response.setBody('{"animal":{"id":1,"name":"chicken","eats":"chicken food","says":"cluck cluck"}}');
        response.setStatusCode(200);
        return response;
    }
}
Test class like below
@isTest
private class AnimalLocatorTest{
    @isTest static  void AnimalLocatorMock1() {
        Test.SetMock(HttpCallOutMock.class, new AnimalLocatorMock());
        string result=AnimalLocator.getAnimalNameById(3);
        string expectedResult='chicken';
        System.assertEquals(result, expectedResult);
    }
}
NOTE:- always try to use Assert


Let us know if this will help you

Thanks
Amit Chaudhary