Hot answers tagged

11

You can create "fake" system objects, but, of course, be wary of doing so in a way that will break their internal implementation. Here's an example of a successful save: Database.SaveResult sr = (Database.SaveResult) JSON.deserialize('{"success":true,"id":"0013000000abcde"}', Database.SaveResult.class); And a failed save: Database.SaveResult sr = (...


8

Check edit history for my initial approach. After revisiting this question and with a bit more experience, I would pursue this path: public class Aggregate { public static List<Aggregate> query(List<AggregateResult> results) { return service.convert(results); } final Map<String, Object> data; public Aggregate(...


8

I typically use a fairly simple pattern and don't bring in a framework. It would look something like the following: public virtual with sharing class MyObjectHelper { static MyObjectHelper instance = new MyObjectHelper(); @TestVisible static void setMock(MyObjectHelper mock) { instance = mock; } public static Boolean canQueryObject(SObjectType ...


7

If your mock does return similar data to the real web service, then your tests can assert that your code that processes the response works correctly. You can also make the mock assert that you send the right request data out to the web service. Setting up a mock means you don't have to add a Test.isRunningTest() in your product code: changing the code under ...


5

Even if you're just returning whatever your mock returns, it can still be beneficial to set up a mock. It can help catch regression errors, like if someone introduces some code that causes a DML before the callout, your unit test would catch that scenario by failing (you're not allowed to callout after a DML statement). The assertion may be pointless, but ...


5

Salesforce has the Stub API to implement mocking: https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_testing_stub_api.htm But, the list of restrictions is pretty eye-watering: The object being mocked must be in the same namespace as the call to the Test.createStub() method. However, the implementation of the StubProvider ...


4

Test.setMock(HttpCalloutMock.class, fakeResponse); Test.setMock(HttpCalloutMock.class, fakeReturn500); You can only set one mock per interface at a time. Your mock class has to be able to send multiple responses, if applicable. ctrl.pullIDAnalyticsReportAPEX(); //INSERTING A NEW CONSUMER_RISK_SUMMARY__C OBJECT ctrl.CallWebService(); //CALLING WESERVICE ...


4

You can mock virtually any relationship if you use a Mock Data Layer Pattern. Imagining your scenario, you could add an Interface to your main class. Let's call it IDataLayer. Add this new interface to the main class (here, called DataLayerHandler.cls) public class DataLayerHandler { public interface IDataLayer { List<Document__c> ...


4

The object must be the object that matches the HttpCalloutMock class: Test.setMock(HttpCalloutMock.class, new MockHTTPResponseGenerator()); If you need different responses, they must all come from the respond method, or you need to use different classes for each mock. global class MockHTTPResponseGenerator implements HttpCalloutMock{ global ...


4

Your mock needs to return a list for the other endpoint: if(request.getEndpoint().contains('services/oauth2/token')) { serialized = '{"'+ token +'":"FAKE-WEB-TOKEN"}'; } else { serialized = '[{"attributes":{"sobjectType":"Tool__c",...},{...},...]'; }


3

Yes you can construct the Messaging.SendEmailResult using the JSON deserializer Messaging.SendEmailResult er =(Messaging.SendEmailResult) JSON.deserialize('{}', Messaging.SendEmailResult.class); System.debug(er); Get your instance. Happy Days.


3

You have to provide the fully qualified parameterized type name to the new operator: List<AccountParameter> testActLst = new List<AccountParameter>(); You can't instantiate the type List as such. That's what these errors are telling you. It found a ( where it was expecting <, from the type name. Then it got confused about the type of your ...


3

@isTest classes are not supposed to be in the code coverage list, and should not count towards the code coverage rules (75% covered). Sometimes, however, things get messed up in the database, and you need to manually delete the erroneous coverage records. To do this: Go to the Developer Console Go to the Query tab Enter the Query SELECT Id, NumLinesCovered ...


3

Test the fact that your trigger makes a callout and the handling of that callout separately. A more testable structure would look something like: public with sharing class CaseTriggerHandler { @TestVisible static Boolean bypassTrigger; final List<Case> newRecords; final Map<Id, Case> oldMap; public CaseTriggerHandler(List<...


3

The problem is with this line: response.put('response__x', a_element); The correct key value is response_x, not response__x.


3

I so much wanted @AdrianLarson original Json.deserialize answer to be right as it is easy to fabricate but while it works at compile time, at run time, the deserialized AggregateResult is empty ( debug displays as {} ). So, here's what I did: Create an AggregateResultProxy object /** * AggregateResult can't be mocked so wrap with AggregateResultProxy * ...


3

A quick search may have found the answer, but it is really simple: Wrap the mock in a test.startTest(); test.startTest(); Test.setMock(HttpCalloutMock.class, new CalloutMock()); update opp; // this update makes callout test.stoptest(); the reason is just like in a non-test environment. You cannot make a callout after doing any dml. Since you ...


3

I cannot mock app-exchange package method, but I can mock my method, which calls the package. This will stop the code entering package and get me to do what I want. public class APIProcessingService { public ppExchangePackage.ApiData.ScreenResponse submit(Id entityId){ AppExchangePackage.Api api = new AppExchangePackage.Api(); ...


2

I think your JSON String is not valid in this line String responseObj = '{"IDScore":"931","Comply360Grade":null,"ErrorInfo":{NULL}}'; Invalid JSON { "IDScore": "931", "Comply360Grade": null, "ErrorInfo": { NULL } } Results in validation Error: Parse error on line 4: ..., "ErrorInfo": { NULL }} ---------------------^ ...


2

No, any code you want to use needs to be deployed. However, if someone (presumably FinancialForce) stepped up and made their package a managed package, then you'd be able to build your code as an extension package. This would actually be ideal if multiple developers started using the same framework, because there'd be a collaborative benefit for everyone. ...


2

Unfortunately you've found one of the current limitations of the stub api. https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_testing_stub_api.htm Apex Stub API Limitations Keep the following limitations in mind when working with the Apex stub API. The object being mocked must be in the same namespace as the call to the Test....


2

As the error message suggests, your mock class hasn't implemented the interface which you have mentioned i.e. you have not implemented the respond method of HttpCalloutMock interface. So, your mock class should be using below line global HttpResponse response(HttpRequest req) {} instead of global HttpResponse response1(HttpRequest req) {} Also, you ...


1

Most info copied from discussion on the sample git commit here. The technique you used to mock out the navigator.geolocation API is fine. The relevant code block from the original question is the following: const mockGeolocation = { getCurrentPosition: jest.fn().mockImplementation((success) => Promise.resolve( success({ ...


1

I was able to fix my problem. It was really about scoping. In the trigger handler (code abbreviated for readability) public inherited sharing class SignatureTriggerHandler implements TriggerHandler { public static Boolean triggerDisabled = false; public Boolean isDisabled() { return triggerDisabled; } public void afterInsert(Map&...


1

Sorry i now i understnding. You don't need this if : if(!Test.isRunningTest()) { res = http.send(request); } else { res= MockApiCalls.WebserviceExpectedResponse1(); } Replace to this : res = http.send(request); because the test class return you response. You set response in class SFEndpointMock. You don't need make ...


1

I vaguely recollect not being able to set values on the mock as if its state is serialised and then deserialised per HTTP callout. So try changing to this pattern: @isTest global class SFEndpointMock implements HttpCalloutMock { private String indicatorVar; global SFEndpointMock(String indicatorVar) { this.indicatorVar = indicatorVar; } ...


1

For REST testing, you don't need to set up Mocks. However, you do need to execute GET(), POST() etc methods for your REST class to perform the HTTP request, and then parse the string from the response. So in your testDoGet method, req.requestURI = 'https://cs23.salesforce.com/services/apexrest/v1/products'; RestContext.request.params.put('countryId', '...


1

In your trigger handler class AccountTriggerHandler create static field @testVisible private static Boolean skipCallout = Test.isRunningTest(); and then before making a callout check: if(!AccountTriggerHandler.skipCallout){ // do callout }


1

In order to have your unit test mock the selector correctly you need to add the following line: mocks.when(selectorMock.sObjectType()).thenReturn(Account.SO‌​bjectType); So your final code would like like the following: @IsTest private class AccountsServiceTest { @IsTest private static void getAccount() { /* Create mocks */ fflib_ApexMocks mocks ...


1

i am using Multiple response for WebServiceMock class so i need to assign a specific URL as following multimock.setStaticResource(endPointURL, 'WooGetIndexMockResponse'); it seems to be not working with this way. then i created Single Request Mock class for each request. in this way we don't need to specify any end-Point URL and my test class working now.


Only top voted, non community-wiki answers of a minimum length are eligible