Created
February 17, 2022 02:04
-
-
Save scottmcclung/21c1a7583f71e43f2e71a4c1b08b24d8 to your computer and use it in GitHub Desktop.
AggregateResult Proxy class for mocking
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /** | |
| * Proxy class for AggregateResult that allows summary data to be mocked in unit tests | |
| * Derived from Adrian Larson's answer here: https://salesforce.stackexchange.com/questions/173193/is-there-a-way-i-can-mock-an-aggregateresult | |
| * | |
| * Usage: | |
| * To create data for the following query | |
| * [SELECT AccountId, COUNT(Id) opportunities FROM Opportunity GROUP BY AccountId] | |
| * | |
| * List<Aggregate> mockData = new Aggregate[]{ | |
| * new Aggregate() | |
| * .put('AccountId', fakeAccountId1) | |
| * .put('opportunties', 10), | |
| * new Aggregate() | |
| * .put('AccountId', fakeAccountId2) | |
| * .put('opportunties', 15), | |
| * } | |
| */ | |
| public class Aggregate | |
| { | |
| public static Aggregate[] convertResults( AggregateResult[] lstResults ) | |
| { | |
| Aggregate[] lstRecords = new Aggregate[]{}; | |
| for( AggregateResult result : lstResults ) | |
| lstRecords.add( new Aggregate( result ) ); | |
| return lstRecords; | |
| } | |
| private final Map<String, Object> data; | |
| public Aggregate( AggregateResult result ) | |
| { | |
| data = result.getPopulatedFieldsAsMap(); | |
| } | |
| @TestVisible | |
| private Aggregate() | |
| { | |
| data = new Map<String, Object>(); | |
| } | |
| public Object get( String alias ) | |
| { | |
| return data.get( alias ); | |
| } | |
| @TestVisible | |
| private Aggregate put( String alias, Object value ) | |
| { | |
| data.put( alias, value ); | |
| return this; | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment