function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Alyssa CooperAlyssa Cooper 

mockhttpresponsegenerator giving error: System.NullPointerException: Attempt to de-reference a null object while validating address on Lead

Hi, I'm very new to Apex (>1 month) and can't debug this error. I've spent about a day on it.  I'm trying to implement the USPS API to validate Lead Addresses

This is my class:
public with sharing class addressValidation {

    String url = 'http:production.shippingapis.com/ShippingAPI.dll?API=Verify&XML=';

    public static HttpResponse getResponse(Lead addressToVerify) {

        String XMLToAttach = '<AddressValidateRequest USERID="<MYIDGOESHERE>">';

        String addr = cleanAddress(addressToVerify);
        XMLToAttach = XMLToAttach + addr;
        Http http = new Http();
        HttpRequest request = new HttpRequest();
        request.setEndpoint('url');
        request.setMethod('GET');

        try {
            HttpResponse res = http.send(request);
            System.debug('Log the status code ' + res.getStatusCode());
            System.debug('log the res body ' + res.getBody());
            Dom.Document doc = res.getBodyDocument();

            Dom.XMLNode address = doc.getRootElement();
            return res;
        }
        catch(Exception e) {
            System.debug('Error calling USPS web service' + e.getMessage());
            return null;
        }
    }


    private static String cleanAddress(Lead address){
        String xmlAddress = '';
        String street = '';
        String city = '';
        String state = '';
        String zip = '';

        street = address.street;
        city = address.city;
        state = address.state;
        zip = address.postalCode;

        xmlAddress = '<Address><street>'+street+'</street>';
        xmlAddress += '<City>'+city+'</City><State>'+state+'</State><Zip>'+zip+'</Zip></Address></AddressValidateRequest>';
        System.debug('This is the xml address being sent' + xmlAddress);
        return xmlAddress;
    }
}
Test method:
/**
 * Created by AlyssaCooper on 3/27/2019.
 */
@IsTest
public with sharing class addressValidationTest {

        @IsTest static void testCallout() {
        Lead testLead = new Lead (
            Street = '123 Street',
            City = 'Boston',
            State = 'Massachusetts',
            PostalCode = '12456',
            LastName = 'Cooper',
            Company = 'Fake Company'
        );
        Test.startTest();

        Test.setMock(HttpCalloutMock.class, new MockHttpResponseGenerator());
        HttpResponse res = addressValidation.getResponse(testLead);

//        Verify response received contains fake values
        String contentType = res.getHeader('Content-Type');
        System.assert(contentType == 'application/xml');
        String actualValue = res.getBody();
        String expectedValue = '{"street": "", "city": "", "state": "", "zip": ""}';
        System.assertEquals(actualValue, expectedValue);
        System.assertEquals(200, res.getStatusCode());
        Test.stopTest();
    }
}

MockHttpResponseGenerator
public with sharing class MockHttpResponseGenerator implements HttpCalloutMock{
    // Implement this interface method
    String url = 'http:production.shippingapis.com/ShippingAPI.dll?API=Verify&XML=';
    public HTTPResponse respond(HTTPRequest req) {

        System.assertEquals('url', req.getEndpoint());
        System.assertEquals('GET', req.getMethod());

        // Create a fake response
        HttpResponse res = new HttpResponse();
        res.setHeader('Content-Type', 'application/xml');
        res.setBody('{"street": "", "city": "", "state": "", "zip": ""}');
        res.setStatusCode(200);
        return res;
    }

}


 
Best Answer chosen by Alyssa Cooper
Santosh Reddy MaddhuriSantosh Reddy Maddhuri

Hi Alyssa Cooper, 

Make following changes to your Test method.
As your header content is application/aml and not application/json need below changes for the test class to work.


MockHttpReponseGenerator:

 

public with sharing class MockHttpResponseGenerator implements HttpCalloutMock{
    // Implement this interface method
    String url = 'http:production.shippingapis.com/ShippingAPI.dll?API=Verify&XML=';
    public HTTPResponse respond(HTTPRequest req) {

        System.assertEquals('url', req.getEndpoint());
        System.assertEquals('GET', req.getMethod());
        string xmlAddress = '<Address>'+
                                 '<street>123 Street</street>'+
                                      '<City>Boston</City>'+
                                                     '<State>Massachusetts</State>'+
                                                  '<Zip>12456</Zip>'+
                                            '</Address>';
                                      
      
        // Create a fake response
        HttpResponse res = new HttpResponse();
        res.setHeader('Content-Type', 'application/xml');
        res.setBody(xmlAddress);
        res.setStatusCode(200);
        return res;
    }

}
 

Test method:
 

/**
 * Created by AlyssaCooper on 3/27/2019.
 */
@IsTest
public with sharing class addressValidationTest {

        @IsTest static void testCallout() {
        Lead testLead = new Lead (
            Street = '123 Street',
            City = 'Boston',
            State = 'Massachusetts',
            PostalCode = '12456',
            LastName = 'Cooper',
            Company = 'Fake Company'
        );
        Test.startTest();

        Test.setMock(HttpCalloutMock.class, new MockHttpResponseGenerator());
        HttpResponse res = addressValidation.getResponse(testLead);

//        Verify response received contains fake values
        String contentType = res.getHeader('Content-Type');
        System.assert(contentType == 'application/xml');
        String actualValue = res.getBody();
        String expectedValue ='<AddressValidateRequest USERID="<12345678>">'+
                                            '<Address>'+
                                                 '<street>123 Street</street>'+
                                                     '<City>Boston</City>'+
                                                     '<State>Massachusetts</State>'+
                                                  '<Zip>12456</Zip>'+
                                            '</Address>'+
                                        '</AddressValidateRequest>' ;
        System.assertEquals(actualValue, expectedValue);
        System.assertEquals(200, res.getStatusCode());
        Test.stopTest();
    }
}
 



Hope this helps!


Regards,

Santosh.

All Answers

Santosh Reddy MaddhuriSantosh Reddy Maddhuri

Hi Alyssa Cooper, 

Make following changes to your Test method.
As your header content is application/aml and not application/json need below changes for the test class to work.


MockHttpReponseGenerator:

 

public with sharing class MockHttpResponseGenerator implements HttpCalloutMock{
    // Implement this interface method
    String url = 'http:production.shippingapis.com/ShippingAPI.dll?API=Verify&XML=';
    public HTTPResponse respond(HTTPRequest req) {

        System.assertEquals('url', req.getEndpoint());
        System.assertEquals('GET', req.getMethod());
        string xmlAddress = '<Address>'+
                                 '<street>123 Street</street>'+
                                      '<City>Boston</City>'+
                                                     '<State>Massachusetts</State>'+
                                                  '<Zip>12456</Zip>'+
                                            '</Address>';
                                      
      
        // Create a fake response
        HttpResponse res = new HttpResponse();
        res.setHeader('Content-Type', 'application/xml');
        res.setBody(xmlAddress);
        res.setStatusCode(200);
        return res;
    }

}
 

Test method:
 

/**
 * Created by AlyssaCooper on 3/27/2019.
 */
@IsTest
public with sharing class addressValidationTest {

        @IsTest static void testCallout() {
        Lead testLead = new Lead (
            Street = '123 Street',
            City = 'Boston',
            State = 'Massachusetts',
            PostalCode = '12456',
            LastName = 'Cooper',
            Company = 'Fake Company'
        );
        Test.startTest();

        Test.setMock(HttpCalloutMock.class, new MockHttpResponseGenerator());
        HttpResponse res = addressValidation.getResponse(testLead);

//        Verify response received contains fake values
        String contentType = res.getHeader('Content-Type');
        System.assert(contentType == 'application/xml');
        String actualValue = res.getBody();
        String expectedValue ='<AddressValidateRequest USERID="<12345678>">'+
                                            '<Address>'+
                                                 '<street>123 Street</street>'+
                                                     '<City>Boston</City>'+
                                                     '<State>Massachusetts</State>'+
                                                  '<Zip>12456</Zip>'+
                                            '</Address>'+
                                        '</AddressValidateRequest>' ;
        System.assertEquals(actualValue, expectedValue);
        System.assertEquals(200, res.getStatusCode());
        Test.stopTest();
    }
}
 



Hope this helps!


Regards,

Santosh.

This was selected as the best answer
Santosh Reddy MaddhuriSantosh Reddy Maddhuri
/**
 * Created by AlyssaCooper on 3/27/2019.
 */
@IsTest
public with sharing class addressValidationTest {

        @IsTest static void testCallout() {
        Lead testLead = new Lead (
            Street = '123 Street',
            City = 'Boston',
            State = 'Massachusetts',
            PostalCode = '12456',
            LastName = 'Cooper',
            Company = 'Fake Company'
        );
        Test.startTest();

        Test.setMock(HttpCalloutMock.class, new MockHttpResponseGenerator());
        HttpResponse res = addressValidation.getResponse(testLead);

//        Verify response received contains fake values
        String contentType = res.getHeader('Content-Type');
        System.assert(contentType == 'application/xml');
        String actualValue = res.getBody();
        String expectedValue = '<Address>'+
                                                 '<street>123 Street</street>'+
                                                     '<City>Boston</City>'+
                                                     '<State>Massachusetts</State>'+
                                                  '<Zip>12456</Zip>'+
                                            '</Address>';
                                       
        System.assertEquals(actualValue, expectedValue);
        System.assertEquals(200, res.getStatusCode());
        Test.stopTest();
    }
}

 
Alyssa CooperAlyssa Cooper
Thank you!