You need to sign in to do that
Don't have an account?

Apex REST callouts trailhead challenge giving System.Nullpointer exception, Please help
Hi,
I have written the below classes as part of the trailhead challenge for Apex REST callouts.
The class -
public class AnimalLocator {
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);
List<Object> animals;
String returnValue;
// parse the JSON response
if (response.getStatusCode() == 200) {
Map<String, Object> result = (Map<String, Object>) JSON.deserializeUntyped(response.getBody());
animals = (List<Object>) result.get('animals');
System.debug(animals);
}
if (animals.size() > 0 && animals != NULL && id < animals.size()) {
returnValue = (String) animals.get(id);
}
return returnValue;
}
}
Mock Response Class -
@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('{"animals": ["majestic badger", "fluffy bunny", "scary bear", "chicken", "mighty moose"]}');
response.setStatusCode(200);
return response;
}
}
Test Class -
@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 );
}
}
I have got 100% code coverage for the main class. But when I check the challenge I get
Challenge Not yet complete... here's what's wrong:
There was an unexpected error in your org which is preventing this assessment check from completing: System.NullPointerException: Attempt to de-reference a null object
Please tell me if any changes to the code is required. It's really frustrating as I am stuck from past 3-4 days with this unit.
Thanks & Regards,
Abhiram Sheshadri
I have written the below classes as part of the trailhead challenge for Apex REST callouts.
The class -
public class AnimalLocator {
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);
List<Object> animals;
String returnValue;
// parse the JSON response
if (response.getStatusCode() == 200) {
Map<String, Object> result = (Map<String, Object>) JSON.deserializeUntyped(response.getBody());
animals = (List<Object>) result.get('animals');
System.debug(animals);
}
if (animals.size() > 0 && animals != NULL && id < animals.size()) {
returnValue = (String) animals.get(id);
}
return returnValue;
}
}
Mock Response Class -
@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('{"animals": ["majestic badger", "fluffy bunny", "scary bear", "chicken", "mighty moose"]}');
response.setStatusCode(200);
return response;
}
}
Test Class -
@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 );
}
}
I have got 100% code coverage for the main class. But when I check the challenge I get
Challenge Not yet complete... here's what's wrong:
There was an unexpected error in your org which is preventing this assessment check from completing: System.NullPointerException: Attempt to de-reference a null object
Please tell me if any changes to the code is required. It's really frustrating as I am stuck from past 3-4 days with this unit.
Thanks & Regards,
Abhiram Sheshadri
All Answers
Hi, Did you click "Run all"
Yeah, I clicked on "Run All". And can you post your mock response as well as test class here, so that I can understand how you solved it.
Try replacing the animal locator.
Keep the other 2 same.
Run All
And check the challenge again
Got the below error.
Error: Compile Error: Non-void method might not return a value or might have statement after a return statement. at line 9 column 13.
Is it the same class which you used for completing the challenge?
I have the same issue. What change u did to fix this issue ?
I changed the code a little bit.You can try the below code.
Executing the 'getAnimalNameById' method on 'AnimalLocator' failed. Make sure the method exists with the name 'getAnimalNameById', is public and static, accepts an Integer and returns a String.
public class AnimalLocator {
public static string getAnimalNameById (integer i)
{
Http ht = new Http();
HttpRequest request = new HttpRequest();
request.setEndpoint('https://th-apex-http-callout.herokuapp.com/animals/' + i);
request.setMethod('GET');
HttpResponse response = ht.send(request);
// If the request is successful, parse the JSON response.
if (response.getStatusCode() == 200)
Map<String, Object> result = (Map<String, Object>)JSON.deserializeUntyped(response.getBody());
Map<string,object> cc = (Map<string,object>) result.get('animals');
return (string) cc.get('name');
}
}
I guess at this line
Map<String, Object> result = (Map<String, Object>)JSON.deserializeUntyped(response.getBody());
Error : variable doesn't exists result.
if (response.getStatusCode() == 200)
Map<String, Object> result = (Map<String, Object>)JSON.deserializeUntyped(response.getBody());
Map<string,object> cc = (Map<string,object>) result.get('animals');
u have not used braces after if condition. So technically only result variable is inside if statement. with local scope. it is not visible outside the if statement.
Correct it as below
if (response.getStatusCode() == 200)
{
Map<String, Object> result = (Map<String, Object>)JSON.deserializeUntyped(response.getBody());
Map<string,object> cc = (Map<string,object>) result.get('animals');
}
I am getting the null pointer exception. My code is similar to that as above. Getting the error as below.
"Challenge Not yet complete... here's what's wrong:
There was an unexpected error in your org which is preventing this assessment check from completing: System.NullPointerException: Attempt to de-reference a null object" What has fixed the null pointer exception please?
Thanks
Bhanu
Please post your code here so that we can take a look at the issue.
Thanks,
Abhiram
There was an unexpected error in your org which is preventing this assessment check from completing: System.NullPointerException: Attempt to de-reference a null object when I went to verify my code. I did verify that I get 100% code coverage and I did verify that everthing worked properly but no matter what I do I still get the same error when I do check challenge
Here are the classes
public class AnimalLocator {
public static String getAnimalNameById(Integer idVal) {
Http http = new Http();
HttpRequest request = new HttpRequest();
request.setEndpoint('https://th-apex-http-callout.herokuapp.com/animals/'+idVal);
String resultValue =NULL;
List<Object> animals;
request.setMethod('GET');
HttpResponse response = new HttpResponse();
response = http.send(request);
// If the request is successful, parse the JSON response.
if (response.getStatusCode() == 200) {
// Deserializes the JSON string into collections of primitive data types.
Map<String, Object> results = (Map<String, Object>) JSON.deserializeUntyped(response.getBody());
animals = (List<Object>) results.get('animals');
System.debug(animals);
if (animals.size() > 0 && animals != NULL && idVal < animals.size()) {
resultValue = (String) animals.get(idVal);
}
}
return resultValue;
}
}
-------------------
@isTest
private class AnimalLocatorTest {
@isTest static void testgetAnimalNameById() {
Test.setMock(HttpCalloutMock.class, new AnimalLocatorMock());
String result = '';
result = AnimalLocator.getAnimalNameById(2);
System.assertEquals('scary bear',result, 'The animals are same.');
}
}
------------------------
@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('{"animals": ["majestic badger", "fluffy bunny", "scary bear", "chicken", "mighty moose"]}');
response.setStatusCode(200);
return response;
}
}
Please suggest.
Thanks
Bhanu
Guys who ever got 100% code coverage and still challenge not complete ,check your httpmock callout class,check if it is like below ,the json response.if not change it and let me know
is
{"animal":{"id":1,"name":"chicken","eats":"chicken food","says":"cluck cluck"}}
So we have to change the httpmock callout class to give the above response.
Modify the test class like below Mock class
Animal Locator class
For the above code,challenge will get cleared.
Thanks for your responses. It finally worked for me. Was making a few mistakes.
In AnimalLocator I coded as
animals = (List<Object>) results.get('animals');
which was returning null. Actually checked the debugger and found it.
corrected as
animals = (List<Object>) results.get('animal');.
Next the statement
if (animals.size() > 0 && animals != NULL && idVal < animals.size()) {
was failing. Not using the right way to check. For the trailhead purpose, commenting it sufficed
Next I decided which Id to search for and used that
In the mock class
replaced
response.setBody('{"animals": ["majestic badger", "fluffy bunny", "scary bear", "chicken", "mighty moose"]}');
with
response.setBody('{"animal":{"id":1,"name":"chicken","eats":"chicken food","says":"cluck cluck"}}');
Made suitable changes in the test class as below
result = AnimalLocator.getAnimalNameById(1);
System.assertEquals('chicken',result, 'The animals are same.');
---
And ran the test. No errors and exceptions. 100% code coverage achieved. Trailhead test cleared :-)
Thanks
Bhanu
Challenge Not yet complete... here's what's wrong:
There was an unexpected error in your org which is preventing this assessment check from completing: System.CalloutException: Unauthorized endpoint, please check Setup->Security->Remote site settings. endpoint = https://th-apex-http-callout.herokuapp.com/animals/99
Can you please post your code here so that we can check what the issue is?
And have you set the remote site settings properly? Is the endpoint effective ?
Thanks,
Abhiram
My remote site setting not set properly.So i got the error.
Now This is ok.
Thanks,
Sudipta
error is for this line in code. i.e. string result = AnimalLocator.getAnimalNameById(3);
I am getting the below error for the animal locator class:
For the line :animals = (Map<String,Object>) result.get('animal');
Error :Illegal Assignment from map to map.
Can anyone assist?
Regards,
Anuja
AnimalLocator:
AnimalLocatorMock
And my AnimalLocatorTest :
I do not get any error in my Test Run , but when I submit I get this error :
Challenge Not yet complete... here's what's wrong:
Executing the 'getAnimalNameById' method on 'AnimalLocator' failed. Make sure the method exists with the name 'getAnimalNameById', is public and static, accepts an Integer and returns a String.
Can anybody please help
Thanks
Hi,
You have to return the animal name in your apex code, but i can see that you are returning null value. Kindly check the code once and try the challenge again.
Thanks
Venkatesh
With 100% code coverage for the main class and presenting the error below:
Challenge Not yet complete ... here's what's wrong:
There was an error in your org which is preventing this assessment check from completing: System.NullPointerException: Attempt to de-reference to null object
I solved with comment of @Sudipta Mondal, where he comments that he had not configured the remote site correctly.
My solution was to select the "Disable Protocol Security" option under Setup -> Remote Sites Settings for the site https://th-apex-http-callout.herokuapp.com
First Register the url in the Remote site settings.
Please try this code if other options fail-
animal locator test
==============
@isTest
private class AnimalLocatorTest{
@isTest
static void testAnimalNameById(){
// Set mock callout class
Test.setMock(HttpCalloutMock.class, new AnimalLocatorMock());
// This causes a fake response to be sent
// from the class that implements HttpCalloutMock.
String result = AnimalLocator.getAnimalNameById(1);
// Verify mock response is not null
System.assertNotEquals(null,result,'The callout returned a null response.');
// Verify status code
System.assertEquals('tiger',result);
}
}
------------------------------
animal locator mock
@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":"tiger","eats":"dear","says":"grow"}}');
response.setStatusCode(200);
return response;
}
}
----------------------
animal locator
public class AnimalLocator{
public static String getAnimalNameById(Integer idAsParam){
String retVal = null;
Http http = new Http();
HttpRequest request = new HttpRequest();
request.setEndpoint('https://th-apex-http-callout.herokuapp.com/animals/'+idAsParam);
request.setMethod('GET');
HttpResponse response = http.send(request);
if (response.getStatusCode() == 200) {
Map<String, Object> results = (Map<String, Object>) JSON.deserializeUntyped(response.getBody());
Map<string,object> mapOfAnimals = (map<string,object>) results.get('animal');
retVal = string.valueof(mapOfAnimals.get('name'));
}
return retVal;
}
}
public class AnimalLocator {
public static String getAnimalNameById(Integer id)
{
String animalName;
System.debug('ID is'+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);
if (response.getStatusCode() == 200) {
// Deserializes the JSON string into collections of primitive data types.
Map<String, Object> results = (Map<String, Object>) JSON.deserializeUntyped(response.getBody());
Map<String, Object> animal = (Map<String, Object>) results.get('animal');
animalName=(String)animal.get('name');
}
System.debug(''+animalName);
return animalName;
}
}
This worked fine for me
Thanks for those three code sections (Apex class. Apex test Class and Apex Mock) worked for me, Understood.
Thank you for the code it worked
can anyone resolve this error? in rest callout challenge
{"animal":{"id":1,"name":"chicken","eats":"chicken food","says":"cluck cluck"}}
Hope that helps.
*****AnimalLocatorMock***** For 200 success response *****AnimalLocatorMockFail ***** FOR 201 Response ****TEST****
Happy Learning :-)
To achieve 100% please, replace your AnimalLocator class
public class AnimalLocator
{
public static string getAnimalNameById(Integer id)
{
String result;
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);
system.debug(response.getBody());
// If the request is successful, parse the JSON response.
if (response.getStatusCode() == 200)
{
// Deserialize the JSON string into collections of primitive data types.
Map<String, Object> results = (Map<String, Object>) JSON.deserializeUntyped(response.getBody());
system.debug(results);
// Cast the values in the 'animals' key as a list
Map<String, Object> animals = (Map<String, Object>) results.get('animal');
system.debug(animals);
System.debug('Received the following animals:');
//System.debug(animals);
System.debug(animals.get('name'));
result = (String)animals.get('name');
}
return result;
}
}
In your code, when the Status code is 200, it will not cover the last line
return null;
to overcome this use a String var to return the result.
I'm doing my 1st steps in dev and would be impossible for me to write all these classes with what I'm learning in trailhead