Any way to easily create unit tests for a wsdl2apex generated Apex class?

I’ve created a new Apex class representing a third-party SOAP web service, using the “Generate from WSDL” button. Now I’d like to deploy this class to my production environment, but I’m getting an error that my test coverage is now below 75%.

The new class is over 2500 lines, and I’d like to avoid manually writing unit tests for the entire class, partly because I’ll only be using small parts of it (but want to keep the whole API available for future use), and partly because perfect functioning of this class is only a convenience, not a necessity for our business.

Is there any way to auto-generate the unit tests, or to otherwise quickly create unit tests that cover enough of my automatically generated Apex class, or possibly to just bypass the code coverage requirement for this class that doesn’t need testing?

Answer

Here is a blog for the solution i used for the Metadata Apex API WSDL test class. The approach uses a semi-generic WebServiceMock implementation and type instantiation to cover the code. You can obtain 100% coverage with this approach. Note that you don’t need to add any real logic to your test, the generated code just needs the return type created and any related types referenced.

This is the pattern used in the blog…

@IsTest
private with sharing class wwwUpsComWsdlXoltwsXavV10Test
{
    private class WebServiceMockImpl implements WebServiceMock
    {
        public void doInvoke(
            Object stub, Object request, Map<String, Object> response,
            String endpoint, String soapAction, String requestName,
            String responseNS, String responseName, String responseType)
        {
            if(request instanceof wwwUpsComXmlschemaXoltwsXavV10.XAVRequest_element)
                response.put('response_x', new wwwUpsComXmlschemaXoltwsXavV10.XAVResponse_element());
            return;
        }
    }
}

@IsTest
private with sharing class wwwUpsComWsdlXoltwsXavV10Test
{
    private static testMethod void coverMethods()
    {
        new wwwUpsComWsdlXoltwsXavV10.XAVPort().ProcessXAV(null, null, null, null);
    }
}

Then for each type add line in the following test method…

@IsTest
private with sharing class wwwUpsComWsdlXoltwsXavV10Test
{
    private static testMethod void coverTypes()
    {
        new wwwUpsComXmlschemaXoltwsCommonV10.TransactionReferenceType();
    }
}

Its currently hand coded, however I’ve been recently playing around with native Apex parsing and code generation with the Tooling API. Though once you get a copy paste flow going from the generated code to the test methods it can be done quite quickly tbh.

Hope this helps…

Attribution
Source : Link , Question Author : Travis , Answer Author : Andrew Fawcett

Leave a Comment