You need to sign in to do that
Don't have an account?
Suresh(Suri)
Need help for Code coverage to json parser in locationcallouts apex class
Hi,
Need to help for code coverage i got 66% but json part not coveing in my controller please look into my code
================Apex Class====================
public class LocationCallouts {
@future (callout=true) // future method needed to run callouts from Triggers
static public void getLocation(id accountId){
// gather account info
Account a = [SELECT BillingCity,BillingCountry,BillingPostalCode,BillingState,BillingStreet FROM Account WHERE id =: accountId];
// create an address string
String address = '';
if (a.BillingStreet != null)
address += a.BillingStreet +', ';
if (a.BillingCity != null)
address += a.BillingCity +', ';
if (a.BillingState != null)
address += a.BillingState +' ';
if (a.BillingPostalCode != null)
address += a.BillingPostalCode +', ';
if (a.BillingCountry != null)
address += a.BillingCountry;
address = EncodingUtil.urlEncode(address, 'UTF-8');
General_Settings__c ge= General_Settings__c.getValues('API Key');
General_Settings__c eurl= General_Settings__c.getValues('Geocoding URL');
System.debug('##########'+eurl);
System.debug('@@@@@@@@@@'+ge);
String geocodingKey = ge.Value__c;
String endpointurl= eurl.Value__c;
// build callout
Http h = new Http();
HttpRequest req = new HttpRequest();
//req.setEndpoint('http://maps.googleapis.com/maps/api/geocode/json?address='+address+'&sensor=false');
req.setEndpoint(endpointurl+'?address='+ address + '&key=' + geocodingKey + '&sensor=false');
req.setMethod('GET');
req.setTimeout(60000);
try{
// callout
HttpResponse res = h.send(req);
System.debug('&&&&&'+res.getBody());
System.debug('#####');
// parse coordinates from response
JSONParser parser = JSON.createParser(res.getBody());
double lat = null;
double lon = null;
while (parser.nextToken() != null) {
if ((parser.getCurrentToken() == JSONToken.FIELD_NAME) &&
(parser.getText() == 'location')){
parser.nextToken(); // object start
while (parser.nextToken() != JSONToken.END_OBJECT){
String txt = parser.getText();
parser.nextToken();
if (txt == 'lat')
lat = parser.getDoubleValue();
else if (txt == 'lng')
lon = parser.getDoubleValue();
}
}
}
// update coordinates if we get back
if (lat != null){
a.GeoLocations__Latitude__s = lat;
a.Location_Latitude__c = lat;
a.GeoLocations__Longitude__s = lon;
a.Location_Longitude__c = lon;
Lat= lat;
Lon= lon;
update a;
}
} catch (Exception e) {
}
}
}
===================ApexTest Class===================
@IsTest(SeeAllData=False)
public class Test_LocationCallouts {
static testMethod void validateLocationCallouts() {
General_Settings__c setting1 = new General_Settings__c();
setting1.Name = 'Geocoding URL';
setting1.Value__c = 'https://maps.googleapis.com/maps/api/geocode/json';
insert setting1;
General_Settings__c setting2 = new General_Settings__c();
setting2.Name = 'API Key';
setting2.Value__c = 'AIzaSyBdTDHIFZgg1lG_p9fCg5QYcWWKrWe6K_E';
insert setting2;
Account a = new Account(Name='Testsup', BillingCountry='USA',BillingState='New Jersey',BillingCity='Cliff Wood',
BillingPostalCode='07010',BillingStreet='cliff wood');
insert a;
LocationCallouts.getLocation(a.id);
Test.startTest();
Test.setMock(HttpCalloutMock.class, new MockHttpResponseGenerator());
Test.stopTest();
HttpResponse res = CalloutClass.getInfoFromExternalService();
}
}
===============Coverage Status===============
Any one help?
Need to help for code coverage i got 66% but json part not coveing in my controller please look into my code
================Apex Class====================
public class LocationCallouts {
@future (callout=true) // future method needed to run callouts from Triggers
static public void getLocation(id accountId){
// gather account info
Account a = [SELECT BillingCity,BillingCountry,BillingPostalCode,BillingState,BillingStreet FROM Account WHERE id =: accountId];
// create an address string
String address = '';
if (a.BillingStreet != null)
address += a.BillingStreet +', ';
if (a.BillingCity != null)
address += a.BillingCity +', ';
if (a.BillingState != null)
address += a.BillingState +' ';
if (a.BillingPostalCode != null)
address += a.BillingPostalCode +', ';
if (a.BillingCountry != null)
address += a.BillingCountry;
address = EncodingUtil.urlEncode(address, 'UTF-8');
General_Settings__c ge= General_Settings__c.getValues('API Key');
General_Settings__c eurl= General_Settings__c.getValues('Geocoding URL');
System.debug('##########'+eurl);
System.debug('@@@@@@@@@@'+ge);
String geocodingKey = ge.Value__c;
String endpointurl= eurl.Value__c;
// build callout
Http h = new Http();
HttpRequest req = new HttpRequest();
//req.setEndpoint('http://maps.googleapis.com/maps/api/geocode/json?address='+address+'&sensor=false');
req.setEndpoint(endpointurl+'?address='+ address + '&key=' + geocodingKey + '&sensor=false');
req.setMethod('GET');
req.setTimeout(60000);
try{
// callout
HttpResponse res = h.send(req);
System.debug('&&&&&'+res.getBody());
System.debug('#####');
// parse coordinates from response
JSONParser parser = JSON.createParser(res.getBody());
double lat = null;
double lon = null;
while (parser.nextToken() != null) {
if ((parser.getCurrentToken() == JSONToken.FIELD_NAME) &&
(parser.getText() == 'location')){
parser.nextToken(); // object start
while (parser.nextToken() != JSONToken.END_OBJECT){
String txt = parser.getText();
parser.nextToken();
if (txt == 'lat')
lat = parser.getDoubleValue();
else if (txt == 'lng')
lon = parser.getDoubleValue();
}
}
}
// update coordinates if we get back
if (lat != null){
a.GeoLocations__Latitude__s = lat;
a.Location_Latitude__c = lat;
a.GeoLocations__Longitude__s = lon;
a.Location_Longitude__c = lon;
Lat= lat;
Lon= lon;
update a;
}
} catch (Exception e) {
}
}
}
===================ApexTest Class===================
@IsTest(SeeAllData=False)
public class Test_LocationCallouts {
static testMethod void validateLocationCallouts() {
General_Settings__c setting1 = new General_Settings__c();
setting1.Name = 'Geocoding URL';
setting1.Value__c = 'https://maps.googleapis.com/maps/api/geocode/json';
insert setting1;
General_Settings__c setting2 = new General_Settings__c();
setting2.Name = 'API Key';
setting2.Value__c = 'AIzaSyBdTDHIFZgg1lG_p9fCg5QYcWWKrWe6K_E';
insert setting2;
Account a = new Account(Name='Testsup', BillingCountry='USA',BillingState='New Jersey',BillingCity='Cliff Wood',
BillingPostalCode='07010',BillingStreet='cliff wood');
insert a;
LocationCallouts.getLocation(a.id);
Test.startTest();
Test.setMock(HttpCalloutMock.class, new MockHttpResponseGenerator());
Test.stopTest();
HttpResponse res = CalloutClass.getInfoFromExternalService();
}
}
===============Coverage Status===============
Any one help?
Rohit Sethi 20
hi Suresh(Suri),
you are setting the mock in test class this will sets the fack respose. So in json you must to be define the location as key and any value so that your condtion get satisfy.
if ((parser.getCurrentToken() == JSONToken.FIELD_NAME) &&
(parser.getText() == 'location')){
example :
res.setBody('{"name":"testrec","billingcountry":"United States","BillingState":"New Jersey","BillingCity":"California","BillingPostalcode":"07010","lat":37.386,"lon":-122.084,"location":Ajmer}');
And one more thing before calling getLocation method you need to be set the mock in test class so use as follow:
example :
Test.startTest();
Test.setMock(HttpCalloutMock.class, new MockHttpResponseGenerator());
LocationCallouts.getLocation(a.id);
Test.stopTest();
Thanks.
May 10, 2016
================================================
hi Suresh(Suri),
you are setting the mock in test class this will sets the fack respose. So in json you must to be define the location as key and any value so that your condtion get satisfy.
if ((parser.getCurrentToken() == JSONToken.FIELD_NAME) &&
(parser.getText() == 'location')){
example :
res.setBody('{"name":"testrec","billingcountry":"United States","BillingState":"New Jersey","BillingCity":"California","BillingPostalcode":"07010","lat":37.386,"lon":-122.084,"location":Ajmer}');
And one more thing before calling getLocation method you need to be set the mock in test class so use as follow:
example :
Test.startTest();
Test.setMock(HttpCalloutMock.class, new MockHttpResponseGenerator());
LocationCallouts.getLocation(a.id);
Test.stopTest();
=====================================================
Hi Rohit,
Its working fine but i modified my code little bit change.
updated code
res.setBody('{"name":"testrec","billingcountry":"United States","BillingState":"New Jersey","BillingCity":"California","BillingPostalcode":"07010","location":{'+'"lat" : 37.79410130,'+'"lon":-122.39510960'+'}}');
I added lat and lang values inside location after that my code executed 100%.
Thanks Rohit for you kind information
All Answers
Rohit Sethi 20
hi Suresh(Suri),
you are setting the mock in test class this will sets the fack respose. So in json you must to be define the location as key and any value so that your condtion get satisfy.
if ((parser.getCurrentToken() == JSONToken.FIELD_NAME) &&
(parser.getText() == 'location')){
example :
res.setBody('{"name":"testrec","billingcountry":"United States","BillingState":"New Jersey","BillingCity":"California","BillingPostalcode":"07010","lat":37.386,"lon":-122.084,"location":Ajmer}');
And one more thing before calling getLocation method you need to be set the mock in test class so use as follow:
example :
Test.startTest();
Test.setMock(HttpCalloutMock.class, new MockHttpResponseGenerator());
LocationCallouts.getLocation(a.id);
Test.stopTest();
Thanks.
May 10, 2016
================================================
hi Suresh(Suri),
you are setting the mock in test class this will sets the fack respose. So in json you must to be define the location as key and any value so that your condtion get satisfy.
if ((parser.getCurrentToken() == JSONToken.FIELD_NAME) &&
(parser.getText() == 'location')){
example :
res.setBody('{"name":"testrec","billingcountry":"United States","BillingState":"New Jersey","BillingCity":"California","BillingPostalcode":"07010","lat":37.386,"lon":-122.084,"location":Ajmer}');
And one more thing before calling getLocation method you need to be set the mock in test class so use as follow:
example :
Test.startTest();
Test.setMock(HttpCalloutMock.class, new MockHttpResponseGenerator());
LocationCallouts.getLocation(a.id);
Test.stopTest();
=====================================================
Hi Rohit,
Its working fine but i modified my code little bit change.
updated code
res.setBody('{"name":"testrec","billingcountry":"United States","BillingState":"New Jersey","BillingCity":"California","BillingPostalcode":"07010","location":{'+'"lat" : 37.79410130,'+'"lon":-122.39510960'+'}}');
I added lat and lang values inside location after that my code executed 100%.
Thanks Rohit for you kind information
I am facing same problem but i am not able to put the code to class/testclass.Can you please show to how to do it.
Below are my code.
//CLASS
public class LocationCallouts {
@future (callout=true) // future method needed to run callouts from Triggers
static public void getLocation(id accountId){
// gather account info
Inventory_Master__c a = [SELECT Address__c,Location__c,Country__c,State__c,City__c FROM Inventory_Master__c WHERE id =: accountId];
// create an address string
String address = '';
if (a.Address__C != null){
if (a.Location__c != null && !address.contains(a.Location__c)){
address += a.Location__c +', ';
}
if (a.City__c != null && !address.contains(a.City__c)){
address += a.City__c +', ';
}
if (a.State__c != null && !address.contains(a.State__c)){
address += a.State__c +', ';
}
if (a.Country__c!= null && !address.contains(a.Country__c)){
address += a.Country__c;
}
}
//address += a.Address__C +', ';
system.debug('Final Address ---> ' + address);
address = EncodingUtil.urlEncode(address, 'UTF-8');
system.debug('After Encoding ---> ' + address);
// build callout
Http h = new Http();
HttpRequest req = new HttpRequest();
req.setEndpoint('https://maps.googleapis.com/maps/api/geocode/json?key=AIzaSyDoOAfjOePA2FVeGSWby02mKZQj-qvZYHM&address='+address+'&sensor=true');
req.setMethod('GET');
req.setTimeout(60000);
try{
// callout
system.debug('ENTERED TRY');
HttpResponse res = h.send(req);
System.debug(res.getBody());
// parse coordinates from response
JSONParser parser = JSON.createParser(res.getBody());
double lat = null;
double lon = null;
while (parser.nextToken() != null) {
if ((parser.getCurrentToken() == JSONToken.FIELD_NAME) &&
(parser.getText() == 'location')){
parser.nextToken(); // object start
while (parser.nextToken() != JSONToken.END_OBJECT){
String txt = parser.getText();
parser.nextToken();
if (txt == 'lat')
{
lat = parser.getDoubleValue();
system.debug('LAT--->>>'+lat);
}
else if (txt == 'lng')
{
lon = parser.getDoubleValue();
system.debug('LON--->>>'+lon);
}
}
}
}
//system.debug('The JSON Response is'+parser);
// update coordinates if we get back
if (lat != null){
system.debug('ENETERED TO UPDATE');
a.Co_ordinates__Latitude__s = lat;
a.Co_ordinates__Longitude__s = lon;
update a;
}
update a;
} catch (Exception e) {
}
}
}
//TEST CLASS
@istest
public class testSetGeolocation
{
static testmethod void SetGeolocation()
{
account acc=new account();
acc.name='Test17';
insert acc;
Inventory_Master__c im=new Inventory_Master__c(Project_Type__c='Standalone Office Building',Property_Owner__c=acc.Id,Location__c ='Marathali',City__c ='Bangalore',State__c = 'Karnataka',Country__c = 'India');
im.Address__c ='4th Cross';
im.Zone__c= 'West Bangalore';
im.Location__c ='Marathali';
im.City__c ='Bangalore';
im.State__c = 'Karnataka';
im.Country__c = 'India';
insert im;
}
}
Please help me out.