When testing the callouts that Chargent makes, you can’t use the HttpCalloutMock class in Salesforce because it must be done from within the Chargent managed package/namespace. To create sample responses and ensure that your code behaves appropriately, use the following workaround:
Use the following code to wrap the call to Chargent Webservices:
if(!test.isRunnungTest()){
//code that makes call out here
}
else{
//create a transaction record manually or set whatever values need for your test to continue
}
Uncommitted Work Errors #
Purpose
When building a custom Visualforce page that will be using Chargent Webservice Methods to process a charge, there is a potential to receive the following error from Salesforce when executing the Chargent Webservice Method:
You have uncommitted work pending. Please commit or rollback before calling out |
Background
One of the framework requirements when developing on the Salesforce platform is that you cannot perform any DML prior to making a callout to any external service in the same transaction. Chargent Webservices, when executed, makes a callout to the appropriate gateway to process the charge; thus, you cannot perform any DML prior to executing a method from Chargent Webservices.
Solution
Within the lifecycle of a Visualforce page, each execution of a controller method from the Visualforce page itself is a separate transaction. The key is that individual execution of the method must come from the page and not from the controller.
The following is an example of a minimalistic page and controller. It is intended only to show the typical pattern that causes the issue.
Error Example:
Page

Controller

When the command button is clicked, it executes the update_and_charge() method. The method updates the Chargent Order record and attempts to execute the charge() method. When the charge() method executes the ChargentWebservices Orders_Click method and attempts to make the callout to the gateway, you will receive the error message.
You must break up the calls using the oncomplete tag on the command button in conjunction with an apex:actionFunction to call the charge() method. This solution is as follows:
Working Example
Page

Controller

On the page, we added an apex:actionFunction to call the charge() method in the controller on completion of the update_and_charge() method. We also removed the call to the charge() method from the controller that was on line 11 in the error example.
In doing this, when clicking the command button, the update_and_charge() method is executed, updating the Chargent Order, completing the transaction, and returning control to the page. The page then calls the actionFunction via the oncomplete tag and executes the charge() method in the controller in a separate transaction without producing any errors.