-
-
Notifications
You must be signed in to change notification settings - Fork 232
Expand file tree
/
Copy pathLoggerMockDataCreator.cls
More file actions
1010 lines (911 loc) · 45.9 KB
/
LoggerMockDataCreator.cls
File metadata and controls
1010 lines (911 loc) · 45.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//------------------------------------------------------------------------------------------------//
// This file is part of the Nebula Logger project, released under the MIT License. //
// See LICENSE file or go to https://github.com/jongpie/NebulaLogger for full license details. //
//------------------------------------------------------------------------------------------------//
/**
* @group Test Utilities
* @description Utility class used to help with generating mock data when writing Apex tests for Nebula Logger.
* These methods are generic, and should work in any Salesforce org.
* These methods can be used when writing Apex tests for plugins.
* @see LoggerMockDataStore
* @see LoggerTestConfigurator
*/
@SuppressWarnings('PMD.CyclomaticComplexity, PMD.CognitiveComplexity, PMD.ExcessivePublicCount, PMD.MethodNamingConventions, PMD.PropertyNamingConventions')
@IsTest
public class LoggerMockDataCreator {
private static final Map<Schema.SObjectType, List<Schema.SObjectField>> SOBJECT_TYPE_TO_ALL_FIELDS = new Map<Schema.SObjectType, List<Schema.SObjectField>>();
private static final Map<Schema.SObjectType, List<Schema.SObjectField>> SOBJECT_TYPE_TO_REQUIRED_FIELDS = new Map<Schema.SObjectType, List<Schema.SObjectField>>();
private static final Map<Schema.SObjectType, Integer> SOBJECT_TYPE_TO_MOCK_ID_COUNT = new Map<Schema.SObjectType, Integer>();
private static Schema.Organization cachedOrganization;
private static Integer userMockUsernameCount = 0;
/**
* @description Instances of `AggregateResult` can not be created directly in Apex.
* This method uses a workaround to generate a mock, although it will not have any fields or aggregate values populated on the object.
* @return The mock instance of `AggregateResult`
*/
public static AggregateResult createAggregateResult() {
Map<String, Object> emptyAggregateKeyValues = new Map<String, Object>();
return (AggregateResult) System.JSON.deserialize(System.JSON.serialize(emptyAggregateKeyValues), AggregateResult.class);
}
/**
* @description Creates a mock instance of `Approval.LockResult` - a mock is used instead of an actual instance
* to help speed up tests, and to support writing unit tests (instead of integration tests). A fake
* record ID is automatically included.
* @param isSuccess Indicates if the generated mock should have `isSuccess`
* @return The mock instance of `Approval.LockResult`
*/
public static Approval.LockResult createApprovalLockResult(Boolean isSuccess) {
return createApprovalLockResult(isSuccess, createId(Schema.Account.SObjectType));
}
/**
* @description Creates a mock instance of `Approval.LockResult` - a mock is used instead of an actual instance
* to help speed up tests, and to support writing unit tests (instead of integration tests)
* @param isSuccess Indicates if the generated mock should have `isSuccess`
* @param recordId The record ID to use within the mock result
* @return The mock instance of `Approval.LockResult`
*/
public static Approval.LockResult createApprovalLockResult(Boolean isSuccess, Id recordId) {
if (isSuccess) {
return (Approval.LockResult) System.JSON.deserialize('{"success": true, "id": "' + recordId + '"}', Approval.LockResult.class);
} else {
return (Approval.LockResult) System.JSON.deserialize(
'{"success":false, "id": "' +
recordId +
'", "errors":[{"message": "insufficient access rights on cross-reference id: ' +
recordId +
'", "statusCode": "INSUFFICIENT_ACCESS_ON_CROSS_REFERENCE_ENTITY"}]}',
Approval.LockResult.class
);
}
}
/**
* @description Creates a mock instance of `Approval.ProcessResult` - a mock is used instead of an actual instance
* to help speed up tests, and to support writing unit tests (instead of integration tests). A fake
* record ID is automatically included.
* @param isSuccess Indicates if the generated mock should have `isSuccess`
* @return The mock instance of `Approval.ProcessResult`
*/
public static Approval.ProcessResult createApprovalProcessResult(Boolean isSuccess) {
return createApprovalProcessResult(isSuccess, createId(Schema.Account.SObjectType));
}
/**
* @description Creates a mock instance of `Approval.ProcessResult` - a mock is used instead of an actual instance
* to help speed up tests, and to support writing unit tests (instead of integration tests)
* @param isSuccess Indicates if the generated mock should have `isSuccess`
* @param recordId The record ID to use within the mock result
* @return The mock instance of `Approval.UnlockResult`
*/
public static Approval.ProcessResult createApprovalProcessResult(Boolean isSuccess, Id recordId) {
if (isSuccess) {
return (Approval.ProcessResult) System.JSON.deserialize('{"success": true, "entityId": "' + recordId + '"}', Approval.ProcessResult.class);
} else {
return (Approval.ProcessResult) System.JSON.deserialize(
'{"success":false, "entityId": "' +
recordId +
'", "errors":[{"message": "No applicable approval process was found.", "statusCode": "NO_APPLICABLE_PROCESS"}]}',
Approval.ProcessResult.class
);
}
}
/**
* @description Creates a mock instance of `Approval.UnlockResult` - a mock is used instead of an actual instance
* to help speed up tests, and to support writing unit tests (instead of integration tests). A fake
* record ID is automatically included.
* @param isSuccess Indicates if the generated mock should have `isSuccess`
* @return The mock instance of `Approval.UnlockResult`
*/
public static Approval.UnlockResult createApprovalUnlockResult(Boolean isSuccess) {
return createApprovalUnlockResult(isSuccess, createId(Schema.Account.SObjectType));
}
/**
* @description Creates a mock instance of `Approval.UnlockResult` - a mock is used instead of an actual instance
* to help speed up tests, and to support writing unit tests (instead of integration tests)
* @param isSuccess Indicates if the generated mock should have `isSuccess`
* @param recordId The record ID to use within the mock result
* @return The mock instance of `Approval.UnlockResult`
*/
public static Approval.UnlockResult createApprovalUnlockResult(Boolean isSuccess, Id recordId) {
if (isSuccess) {
return (Approval.UnlockResult) System.JSON.deserialize('{"success": true, "id": "' + recordId + '"}', Approval.UnlockResult.class);
} else {
return (Approval.UnlockResult) System.JSON.deserialize(
'{"success":false, "id": "' +
recordId +
'", "errors":[{"message": "insufficient access rights on cross-reference id: ' +
recordId +
'", "statusCode": "INSUFFICIENT_ACCESS_ON_CROSS_REFERENCE_ENTITY"}]}',
Approval.UnlockResult.class
);
}
}
/**
* @description Creates a mock instance of `Database.DeleteResult` - a mock is used instead of an actual instance
* to help speed up tests, and to support writing unit tests (instead of integration tests). A fake
* record ID is automatically included.
* @param isSuccess Indicates if the generated mock should have `isSuccess`
* @return The mock instance of `Database.DeleteResult`
*/
public static Database.DeleteResult createDatabaseDeleteResult(Boolean isSuccess) {
return createDatabaseDeleteResult(isSuccess, createId(Schema.Account.SObjectType));
}
/**
* @description Creates a mock instance of `Database.DeleteResult` - a mock is used instead of an actual instance
* to help speed up tests, and to support writing unit tests (instead of integration tests)
* @param isSuccess Indicates if the generated mock should have `isSuccess`
* @param recordId The record ID to use within the mock result
* @return The mock instance of `Database.DeleteResult`
*/
public static Database.DeleteResult createDatabaseDeleteResult(Boolean isSuccess, Id recordId) {
if (isSuccess) {
return (Database.DeleteResult) System.JSON.deserialize('{"success": true, "id": "' + recordId + '"}', Database.DeleteResult.class);
} else {
return (Database.DeleteResult) System.JSON.deserialize(
'{"success":false, "id": "' + recordId + '", "errors":[{"message": "Could not delete...", "statusCode": "DELETE_FAILED"}]}',
Database.DeleteResult.class
);
}
}
/**
* @description Creates a list of mock instances of `Database.DeleteResult` - mocks are used instead of actual instances
* to help speed up tests, and to support writing unit tests (instead of integration tests)
* @param numOfResults The number of `Database.DeleteResult` instances to create
* @param isSuccess Indicates if the generated mocks should have `isSuccess`
* @return The list of mock instances of `Database.DeleteResult`
*/
public static List<Database.DeleteResult> createDatabaseDeleteResultList(Integer numOfResults, Boolean isSuccess) {
List<Database.DeleteResult> deleteResults = new List<Database.DeleteResult>();
for (Integer i = 0; i < numOfResults; i++) {
deleteResults.add(LoggerMockDataCreator.createDatabaseDeleteResult(isSuccess));
}
return deleteResults;
}
/**
* @description Creates a mock instance of `Database.EmptyRecycleBinResult` - a mock is used instead of an actual instance
* to help speed up tests, and to support writing unit tests (instead of integration tests). A fake
* record ID is automatically included.
* @param isSuccess Indicates if the generated mock should have `isSuccess`
* @return The mock instance of `Database.EmptyRecycleBinResult`
*/
public static Database.EmptyRecycleBinResult createDatabaseEmptyRecycleBinResult(Boolean isSuccess) {
return createDatabaseEmptyRecycleBinResult(isSuccess, createId(Schema.Account.SObjectType));
}
/**
* @description Creates a mock instance of `Database.EmptyRecycleBinResult` - a mock is used instead of an actual instance
* to help speed up tests, and to support writing unit tests (instead of integration tests)
* @param isSuccess Indicates if the generated mock should have `isSuccess`
* @param recordId The record ID to use within the mock result
* @return The mock instance of `Database.EmptyRecycleBinResult`
*/
public static Database.EmptyRecycleBinResult createDatabaseEmptyRecycleBinResult(Boolean isSuccess, Id recordId) {
if (isSuccess) {
return (Database.EmptyRecycleBinResult) System.JSON.deserialize('{"success": true, "id": "' + recordId + '"}', Database.EmptyRecycleBinResult.class);
} else {
return (Database.EmptyRecycleBinResult) System.JSON.deserialize(
'{"success":false, "id": "' +
recordId +
'", "errors":[{"message": "invalid record id; no recycle bin entry found", "statusCode": "INVALID_ID_FIELD"}]}',
Database.EmptyRecycleBinResult.class
);
}
}
/**
* @description Creates a list of mock instances of `Database.EmptyRecycleBinResult` - mocks are used instead of actual
* instances to help speed up tests, and to support writing unit tests (instead of integration tests)
* @param numOfResults The number of `Database.EmptyRecycleBinResult` instances to create
* @param isSuccess Indicates if the generated mocks should have `isSuccess`
* @return The list of mock instances of `Database.EmptyRecycleBinResult`
*/
public static List<Database.EmptyRecycleBinResult> createDatabaseEmptyRecycleBinResultList(Integer numOfResults, Boolean isSuccess) {
List<Database.EmptyRecycleBinResult> emptyRecycleBinResults = new List<Database.EmptyRecycleBinResult>();
for (Integer i = 0; i < numOfResults; i++) {
emptyRecycleBinResults.add(LoggerMockDataCreator.createDatabaseEmptyRecycleBinResult(isSuccess));
}
return emptyRecycleBinResults;
}
/**
* @description Creates a mock instance of `Database.LeadConvertResult` - a mock is used instead of an actual instance
* to help speed up tests, and to support writing unit tests (instead of integration tests). A fake
* record ID is automatically included.
* @param isSuccess Indicates if the generated mock should have `isSuccess`
* @return The mock instance of `Database.LeadConvertResult`
*/
public static Database.LeadConvertResult createDatabaseLeadConvertResult(Boolean isSuccess) {
return createDatabaseLeadConvertResult(isSuccess, createId(Schema.Lead.SObjectType));
}
/**
* @description Creates a mock instance of `Database.LeadConvertResult` - a mock is used instead of an actual instance
* to help speed up tests, and to support writing unit tests (instead of integration tests)
* @param isSuccess Indicates if the generated mock should have `isSuccess`
* @param recordId The record ID to use within the mock result
* @return The mock instance of `Database.LeadConvertResult`
*/
public static Database.LeadConvertResult createDatabaseLeadConvertResult(Boolean isSuccess, Id recordId) {
if (isSuccess) {
return (Database.LeadConvertResult) System.JSON.deserialize('{"success": true, "leadid": "' + recordId + '"}', Database.LeadConvertResult.class);
} else {
return (Database.LeadConvertResult) System.JSON.deserialize(
'{"success":false, "leadid": "' + recordId + '", "errors":[{"message": "convertedStatus is required...", "statusCode": "REQUIRED_FIELD_MISSING"}]}',
Database.LeadConvertResult.class
);
}
}
/**
* @description Creates a list of mock instances of `Database.LeadConvertResult` - mocks are used instead of actual instances
* to help speed up tests, and to support writing unit tests (instead of integration tests)
* @param numOfResults The number of `Database.LeadConvertResult` instances to create
* @param isSuccess Indicates if the generated mocks should have `isSuccess`
* @return The list of mock instances of `Database.LeadConvertResult`
*/
public static List<Database.LeadConvertResult> createDatabaseLeadConvertResultList(Integer numOfResults, Boolean isSuccess) {
List<Database.LeadConvertResult> leadConvertResults = new List<Database.LeadConvertResult>();
for (Integer i = 0; i < numOfResults; i++) {
leadConvertResults.add(LoggerMockDataCreator.createDatabaseLeadConvertResult(isSuccess));
}
return leadConvertResults;
}
/**
* @description Creates a mock instance of `Database.MergeResult` - a mock is used instead of an actual instance
* to help speed up tests, and to support writing unit tests (instead of integration tests). A fake
* record ID is automatically included.
* @param isSuccess Indicates if the generated mock should have `isSuccess`
* @return The list of mock instances of `Database.MergeResult`
*/
public static Database.MergeResult createDatabaseMergeResult(Boolean isSuccess) {
return createDatabaseMergeResult(isSuccess, createId(Schema.Account.SObjectType));
}
/**
* @description Creates a mock instance of `Database.MergeResult` - a mock is used instead of an actual instance
* to help speed up tests, and to support writing unit tests (instead of integration tests)
* @param isSuccess Indicates if the generated mock should have `isSuccess`
* @param recordId The record ID to use within the mock result
* @return The mock instance of `Database.MergeResult`
*/
public static Database.MergeResult createDatabaseMergeResult(Boolean isSuccess, Id recordId) {
if (isSuccess) {
return (Database.MergeResult) System.JSON.deserialize('{"success": true, "id": "' + recordId + '"}', Database.MergeResult.class);
} else {
return (Database.MergeResult) System.JSON.deserialize(
'{"success":false,"errors":[{"message": "Could not merge...", "statusCode": "MERGE_FAILED"}]}',
Database.MergeResult.class
);
}
}
/**
* @description Creates a list of mock instances of `Database.MergeResult` - a mock is used instead of an actual
* instance to help speed up tests, and to support writing unit tests (instead of integration tests)
* @param numOfResults Indicates how many `Database.MergeResult` instances to create
* @param isSuccess Indicates if the generated mocks should have `isSuccess`
* @return The list of mock instances of `Database.MergeResult`
*/
public static List<Database.MergeResult> createDatabaseMergeResultList(Integer numOfResults, Boolean isSuccess) {
List<Database.MergeResult> mergeResults = new List<Database.MergeResult>();
for (Integer i = 0; i < numOfResults; i++) {
mergeResults.add(LoggerMockDataCreator.createDatabaseMergeResult(isSuccess));
}
return mergeResults;
}
/**
* @description Creates a mock instance of `Database.SaveResult` - a mock is used instead of an actual instance
* to help speed up tests, and to support writing unit tests (instead of integration tests). A fake
* record ID is automatically included.
* @param isSuccess Indicates if the generated mock should have `isSuccess`
* @return The mock instance of `Database.SaveResult`
*/
public static Database.SaveResult createDatabaseSaveResult(Boolean isSuccess) {
return createDatabaseSaveResult(isSuccess, createId(Schema.Account.SObjectType));
}
/**
* @description Creates a mock instance of `Database.SaveResult` - a mock is used instead of an actual instance
* to help speed up tests, and to support writing unit tests (instead of integration tests)
* @param isSuccess Indicates if the generated mock should have `isSuccess`
* @param recordId The record ID to use within the mock result
* @return The mock instance of `Database.SaveResult`
*/
public static Database.SaveResult createDatabaseSaveResult(Boolean isSuccess, Id recordId) {
if (isSuccess) {
return (Database.SaveResult) System.JSON.deserialize('{"success": true, "id": "' + recordId + '"}', Database.SaveResult.class);
} else {
return (Database.SaveResult) System.JSON.deserialize(
'{"success":false,"errors":[{"message": "Could not save...", "statusCode": "FIELD_CUSTOM_VALIDATION_EXCEPTION", "fields": ["Name"]}]}',
Database.SaveResult.class
);
}
}
/**
* @description Creates a list of mock instances of `Database.SaveResult` - mocks are used instead of actual instances
* to help speed up tests, and to support writing unit tests (instead of integration tests)
* @param numOfResults The number of `Database.SaveResult` instances to create
* @param isSuccess Indicates if the generated mocks should have `isSuccess`
* @return The list of mock instances of `Database.SaveResult`
*/
public static List<Database.SaveResult> createDatabaseSaveResultList(Integer numOfResults, Boolean isSuccess) {
List<Database.SaveResult> saveResults = new List<Database.SaveResult>();
for (Integer i = 0; i < numOfResults; i++) {
saveResults.add(LoggerMockDataCreator.createDatabaseSaveResult(isSuccess));
}
return saveResults;
}
/**
* @description Creates a mock instance of `Database.UndeleteResult` - a mock is used instead of an actual instance
* to help speed up tests, and to support writing unit tests (instead of integration tests). A fake
* record ID is automatically included.
* @param isSuccess Indicates if the generated mock should have `isSuccess`
* @return The mock instance of `Database.UndeleteResult`
*/
public static Database.UndeleteResult createDatabaseUndeleteResult(Boolean isSuccess) {
return createDatabaseUndeleteResult(isSuccess, createId(Schema.Account.SObjectType));
}
/**
* @description Creates a mock instance of `Database.UndeleteResult` - a mock is used instead of an actual instance
* to help speed up tests, and to support writing unit tests (instead of integration tests)
* @param isSuccess Indicates if the generated mock should have `isSuccess`
* @param recordId The record ID to use within the mock result
* @return The mock instance of `Database.UndeleteResult`
*/
public static Database.UndeleteResult createDatabaseUndeleteResult(Boolean isSuccess, Id recordId) {
if (isSuccess) {
return (Database.UndeleteResult) System.JSON.deserialize('{"success": true, "id": "' + recordId + '"}', Database.UndeleteResult.class);
} else {
return (Database.UndeleteResult) System.JSON.deserialize(
'{"success":false,"errors":[{"message": "Could not undelete...", "statusCode": "FIELD_CUSTOM_VALIDATION_EXCEPTION", "fields": ["Name"]}]}',
Database.UndeleteResult.class
);
}
}
/**
* @description Creates a list of mock instances of `Database.UndeleteResult` - mocks are used instead of actual instances
* to help speed up tests, and to support writing unit tests (instead of integration tests)
* @param numOfResults The number of `Database.UndeleteResult` instances to create
* @param isSuccess Indicates if the generated mocks should have `isSuccess`
* @return The list of mock instances of `Database.UndeleteResult`
*/
public static List<Database.UndeleteResult> createDatabaseUndeleteResultList(Integer numOfResults, Boolean isSuccess) {
List<Database.UndeleteResult> undeleteResults = new List<Database.UndeleteResult>();
for (Integer i = 0; i < numOfResults; i++) {
undeleteResults.add(LoggerMockDataCreator.createDatabaseUndeleteResult(isSuccess));
}
return undeleteResults;
}
/**
* @description Creates a mock instance of `Database.UpsertResult` - a mock is used instead of an actual instance
* to help speed up tests, and to support writing unit tests (instead of integration tests). A fake
* record ID is automatically included.
* @param isSuccess Indicates if the generated mock should have `isSuccess`
* @param isCreated Indicates if the generated mock should have `isCreated`
* @return The mock instance of `Database.UpsertResult`
*/
public static Database.UpsertResult createDatabaseUpsertResult(Boolean isSuccess, Boolean isCreated) {
return createDatabaseUpsertResult(isSuccess, isCreated, createId(Schema.Account.SObjectType));
}
/**
* @description Creates a mock instance of `Database.UpsertResult` - a mock is used instead of an actual instance
* to help speed up tests, and to support writing unit tests (instead of integration tests)
* @param isSuccess Indicates if the generated mock should have `isSuccess`
* @param isCreated Indicates if the generated mock should have `isCreated`
* @param recordId The record ID to use within the mock result
* @return The mock instance of `Database.UpsertResult`
*/
public static Database.UpsertResult createDatabaseUpsertResult(Boolean isSuccess, Boolean isCreated, Id recordId) {
if (isSuccess) {
return (Database.UpsertResult) System.JSON.deserialize(
'{"success": ' + isSuccess + ', "created": ' + isCreated + ', "id": "' + recordId + '"}',
Database.UpsertResult.class
);
} else {
return (Database.UpsertResult) System.JSON.deserialize(
'{"success":false, "created":' +
isCreated +
', "errors":[{"message": "Could not upsert...", "statusCode": "FIELD_CUSTOM_VALIDATION_EXCEPTION", "fields": ["Name"]}]}',
Database.UpsertResult.class
);
}
}
/**
* @description Creates a list of mock instances of `Database.UpsertResult` - mocks are used instead of actual instances
* to help speed up tests, and to support writing unit tests (instead of integration tests). A fake
* record ID is automatically included.
* @param numOfResults The number of `Database.UpsertResult` instances to create
* @param isSuccess Indicates if the generated mock should have `isSuccess`
* @param isCreated Indicates if the generated mock should have `isCreated`
* @return The list of mock instances of `Database.UpsertResult`
*/
public static List<Database.UpsertResult> createDatabaseUpsertResultList(Integer numOfResults, Boolean isSuccess, Boolean isCreated) {
List<Database.UpsertResult> upsertResults = new List<Database.UpsertResult>();
for (Integer i = 0; i < numOfResults; i++) {
upsertResults.add(LoggerMockDataCreator.createDatabaseUpsertResult(isSuccess, isCreated));
}
return upsertResults;
}
/**
* @description Generates an instance of the class `MockHttpCallout` that implements the interface `System.HttpCalloutMock`.
* This can be used when testing batch jobs.
* @return The instance of `MockHttpCallout`
*/
public static MockHttpCallout createHttpCallout() {
return new MockHttpCallout();
}
/**
* @description Generates an instance of `HttpRequest`. This can be used when testing logging capabilities for instances of `HttpRequest`.
* @return The instance of `HttpRequest`
*/
public static System.HttpRequest createHttpRequest() {
System.HttpRequest request = new System.HttpRequest();
request.setBody('Hello, world!');
request.setCompressed(true);
request.setEndpoint('https://fake.salesforce.com');
request.setMethod('GET');
return request;
}
/**
* @description Generates an instance of `HttpResponse`. This can be used when testing logging capabilities for instances of `HttpResponse`.
* @return The instance of `HttpResponse`
*/
public static System.HttpResponse createHttpResponse() {
System.HttpResponse response = new System.HttpResponse();
response.setBody('Hello, world!');
response.setHeader('someKey', 'some string value');
response.setHeader('anotherKey', 'an amazing example value, wow');
response.setStatus('STATUS_GOOD_JOB_YOU_DID_IT');
response.setStatusCode(201);
return response;
}
/**
* @description Generates a mock record ID for the provided SObject Type
* @param sobjectType The SObject Type for the generated mock record ID
* @return The mock record ID for the specified SObject Type
*/
public static String createId(Schema.SObjectType sobjectType) {
Integer recordIdNumber = 1;
if (SOBJECT_TYPE_TO_MOCK_ID_COUNT.containsKey(sobjectType)) {
recordIdNumber = SOBJECT_TYPE_TO_MOCK_ID_COUNT.get(sobjectType);
}
String recordIdSuffix = String.valueOf(recordIdNumber++);
SOBJECT_TYPE_TO_MOCK_ID_COUNT.put(sobjectType, recordIdNumber);
String recordIdKeyPrefix = sobjectType.getDescribe().getKeyPrefix();
Integer idFieldLength = sobjectType.getDescribe().fields.getMap().get('Id').getDescribe().getLength();
Integer recordIdCenterLength = idFieldLength - recordIdKeyPrefix.length() - recordIdSuffix.length();
return recordIdKeyPrefix + '0'.repeat(recordIdCenterLength) + recordIdSuffix;
}
/**
* @description Creates a new builder instance for the specified `SObjectType`, including creating a
* new `SObject` record. The new `SObject` record is created with any default field values that
* have been configured on the `SObjectType`.
* @param sobjectType The `SObjectType` to use for generating a new test `SObject` record
* @return A new instance of `SObjectTestDataBuilder` for the specified `SObjectType`
*/
public static SObjectTestDataBuilder createDataBuilder(Schema.SObjectType sobjectType) {
return new SObjectTestDataBuilder(sobjectType);
}
/**
* @description Creates a new builder instance for the specified `SObject` record
* @param record The existing test `SObject` record to populate with sample data
* @return A new instance of `SObjectTestDataBuilder` for the specified `SObject`
*/
public static SObjectTestDataBuilder createDataBuilder(SObject record) {
return new SObjectTestDataBuilder(record);
}
/**
* @description Creates a `Schema.User` record for testing purposes, using the current user's profile
* @return The generated `Schema.User` record - it is not automatically inserted into the database.
*/
public static Schema.User createUser() {
return createUser(System.UserInfo.getProfileId());
}
/**
* @description Creates a `Schema.User` record for testing purposes, using the specified profile ID
* @param profileId The `Schema.Profile` ID to use for the created `Schema.User`
* @return The generated `Schema.User` record - it is not automatically inserted into the database.
*/
public static Schema.User createUser(Id profileId) {
String uniqueString = Logger.getTransactionId() + (userMockUsernameCount++) + '@test.com';
return new Schema.User(
Alias = 'user_xyz',
Email = 'user_xyz@test.com.net.org',
EmailEncodingKey = 'ISO-8859-1',
FederationIdentifier = uniqueString + '.sso',
LanguageLocaleKey = 'en_US',
LastName = 'Test Userson',
LocaleSidKey = 'en_US',
ProfileId = profileId,
TimeZoneSidKey = 'America/Los_Angeles',
Username = uniqueString
);
}
/**
* @description Queries for the `Schema.Organization` record for the current environment.
* @return The matching `Schema.Organization` record
*/
public static Schema.Organization getOrganization() {
// TODO Switch to creating mock instance of Schema.Organization with sensible defaults that tests can then update as needed for different scenarios
if (cachedOrganization == null) {
cachedOrganization = [SELECT Id, Name, InstanceName, IsSandbox, NamespacePrefix, OrganizationType, TrialExpirationDate FROM Organization LIMIT 1];
}
return cachedOrganization;
}
/**
* @description Returns the current environment's type - Scratch Org, Sandbox, or Production.
* @return The environment type
*/
public static String getOrganizationEnvironmentType() {
Schema.Organization organization = getOrganization();
String orgEnvironmentType;
if (organization.IsSandbox && organization.TrialExpirationDate != null) {
orgEnvironmentType = 'Scratch Org';
} else if (organization.IsSandbox) {
orgEnvironmentType = 'Sandbox';
} else {
orgEnvironmentType = 'Production';
}
return orgEnvironmentType;
}
/**
* @description Returns the current user
* @return The matching `Schema.User` record
*/
public static Schema.User getUser() {
return getUser(System.UserInfo.getUserId());
}
/**
* @description Returns the specified user
* @param userId The ID of the `Schema.User` record to query
* @return The matching `Schema.User` record
*/
public static Schema.User getUser(Id userId) {
return [
SELECT
FederationIdentifier,
Id,
Profile.Name,
Profile.UserLicenseId,
Profile.UserLicense.LicenseDefinitionKey,
Profile.UserLicense.Name,
Username,
UserRole.Name
FROM User
WHERE Id = :userId
];
}
/**
* @description Creates and inserts a `Schema.Group` record for testing queues, using the specified SObject Type
* @param queueDeveloperName The developer name to use for the new queue (stored in `Schema.Group.DeveloperName`)
* @param sobjectType The `SObjectType` that the queue should be able to own (stored in `QueueSObject.SObjectType`)
* @return The inserted `Schema.Group` record - it is automatically inserted into the database, as well as 1 child `QueueSObject` record.
*/
public static Schema.Group insertQueue(String queueDeveloperName, Schema.SObjectType sobjectType) {
Schema.Group queue = new Schema.Group(DeveloperName = queueDeveloperName, Name = queueDeveloperName, Type = 'Queue');
insert queue;
// To avoid a MIXED_DML_OPERATION exception, use System.runs() for inserting the QueueSObject record
System.runAs(new Schema.User(Id = System.UserInfo.getUserId())) {
QueueSObject queueSObject = new QueueSObject(QueueId = queue.Id, SObjectType = sobjectType.toString());
insert queueSObject;
}
return queue;
}
/**
* @description Sets a value for read-only fields that typically cannot be directly set on some SObjects
* @param record The `SObject` record to update
* @param field The `Schema.SObjectField` for the field to update
* @param value The field value to populate on the provied `SObject` record
* @return A new copy of the original `SObject` record that has the specified read-only field populated
*/
public static SObject setReadOnlyField(SObject record, Schema.SObjectField field, Object value) {
return setReadOnlyField(record, new Map<Schema.SObjectField, Object>{ field => value });
}
/**
* @description Sets values for read-only fields that typically cannot be directly set on some SObjects
* @param record record description
* @param changesToFields An instance of `Map<Schema.SObjectField, Object> containing the read-only fields and corresponding
* field values to populate on the provied `SObject` record
* @return A new copy of the original `SObject` record that has the specified read-only fields populated
*/
public static SObject setReadOnlyField(SObject record, Map<Schema.SObjectField, Object> changesToFields) {
String serializedRecord = System.JSON.serialize(record);
Map<String, Object> deserializedRecordMap = (Map<String, Object>) System.JSON.deserializeUntyped(serializedRecord);
// Loop through the deserialized record map and put the field & value
// Since it's a map, if the field already exists on the SObject, it's updated (or added if it wasn't there already)
for (Schema.SObjectField sobjectField : changesToFields.keySet()) {
String fieldName = sobjectField.toString();
deserializedRecordMap.put(fieldName, changesToFields.get(sobjectField));
}
serializedRecord = System.JSON.serialize(deserializedRecordMap);
return (SObject) System.JSON.deserialize(serializedRecord, SObject.class);
}
@SuppressWarnings('PMD.ApexDoc')
public class MockBatchableContext implements Database.BatchableContext {
private Id childJobId;
private Id jobId;
public MockBatchableContext() {
this.jobId = createId(Schema.AsyncApexJob.SObjectType);
this.childJobId = createId(Schema.AsyncApexJob.SObjectType);
}
public MockBatchableContext(Id jobId) {
this(jobId, null);
}
public MockBatchableContext(Id jobId, Id childJobId) {
this.jobId = jobId;
this.childJobId = childJobId;
}
public Id getJobId() {
return this.jobId;
}
public Id getChildJobId() {
return this.childJobId;
}
}
@SuppressWarnings('PMD.ApexDoc')
public class MockFinalizerContext implements System.FinalizerContext {
private Exception apexException;
private Id asyncApexJobId;
public MockFinalizerContext() {
this.asyncApexJobId = createId(Schema.AsyncApexJob.SObjectType);
}
public MockFinalizerContext(Id asyncApexJobId) {
this.asyncApexJobId = asyncApexJobId;
}
public MockFinalizerContext(Exception ex) {
this();
this.apexException = ex;
}
public Id getAsyncApexJobId() {
return this.asyncApexJobId;
}
public Exception getException() {
return this.apexException;
}
public System.ParentJobResult getResult() {
return this.apexException == null ? System.ParentJobResult.SUCCESS : System.ParentJobResult.UNHANDLED_EXCEPTION;
}
public String getRequestId() {
return System.Request.getCurrent().getRequestId();
}
}
@SuppressWarnings('PMD.ApexDoc')
public class MockQueueableContext implements System.QueueableContext {
private Id jobId;
public MockQueueableContext() {
this.jobId = createId(Schema.AsyncApexJob.SObjectType);
}
public MockQueueableContext(Id jobId) {
this.jobId = jobId;
}
public Id getJobId() {
return this.jobId;
}
}
@SuppressWarnings('PMD.ApexDoc')
public class MockSchedulableContext implements System.SchedulableContext {
private Id triggerId;
public MockSchedulableContext() {
this.triggerId = createId(Schema.CronTrigger.SObjectType);
}
public MockSchedulableContext(Id triggerId) {
this.triggerId = triggerId;
}
public Id getTriggerId() {
return this.triggerId;
}
}
@SuppressWarnings('PMD.ApexDoc, PMD.EmptyStatementBlock')
public class MockHttpCallout implements System.HttpCalloutMock {
public System.HttpRequest request { get; private set; }
public System.HttpResponse response { get; private set; }
public String responseBody { get; private set; }
public Integer statusCode { get; private set; }
public String statusMessage { get; private set; }
public MockHttpCallout() {
}
public MockHttpCallout setResponseBody(String responseBody) {
this.responseBody = responseBody;
return this;
}
public MockHttpCallout setStatusCode(Integer statusCode) {
this.statusCode = statusCode;
return this;
}
public MockHttpCallout setStatus(String statusMessage) {
this.statusMessage = statusMessage;
return this;
}
public System.HttpResponse respond(System.HttpRequest request) {
this.request = request;
this.response = new System.HttpResponse();
if (String.isNotBlank(this.responseBody)) {
response.setBody(this.responseBody);
}
response.setStatusCode(this.statusCode);
if (String.isNotBlank(this.statusMessage)) {
response.setStatus(this.statusMessage);
}
return response;
}
}
/**
* @description Class used to create or update an `SObject` record with static fake data.
* This is useful in situations where you need to have fields populated, but the specific
* values used are not relevant to a particular test method.
* This class can be used when Apex writing tests for plugins.
*/
public without sharing class SObjectTestDataBuilder {
private final Schema.SObjectType sobjectType;
private final SObject record;
/**
* @description Creates a new builder instance for the specified `SObjectType`, including creating a
* new `SObject` record. The new `SObject` record is created with any default field values that
* have been configured on the `SObjectType`.
* @param sobjectType The `SObjectType` to use for generating a new test `SObject` record
*/
private SObjectTestDataBuilder(Schema.SObjectType sobjectType) {
this(sobjectType.newSObject(null, true));
}
/**
* @description Creates a new builder instance for the specified `SObject` record
* @param record The existing test `SObject` record to populate with sample data
*/
private SObjectTestDataBuilder(SObject record) {
this.record = record;
this.sobjectType = record.getSObjectType();
this.loadFields();
}
/**
* @description Generates a mock record ID for the builder's `SObject` record
* @return The same instance of `SObjectTestDataBuilder`, useful for chaining methods
*/
public SObjectTestDataBuilder populateMockId() {
this.record.Id = createId(this.sobjectType);
return this;
}
/**
* @description Sets a value on all editable fields, unless the `SObject` record already had a value specified for a field (including `null`)
* @return The `SObject` record, with all editable fields populated
*/
public SObjectTestDataBuilder populateAllFields() {
this.setUnpopulatedFieldsOnRecord(SOBJECT_TYPE_TO_ALL_FIELDS.get(this.sobjectType));
return this;
}
/**
* @description Sets a value on all editable required fields, unless the `SObject` record already had a value specified for a field (including `null`)
* @return The `SObject` record, with all editable required fields populated
*/
public SObjectTestDataBuilder populateRequiredFields() {
this.setUnpopulatedFieldsOnRecord(SOBJECT_TYPE_TO_REQUIRED_FIELDS.get(this.sobjectType));
return this;
}
/**
* @description Returns the builder's `SObject` record with fields populated based on
* which builder methods have been called
* @return The builder's `SObject` record that was either provided by the calling code, or generated
* by the builder (depending on which constructor was used for `SObjectTestDataBuilder`)
*/
public SObject getRecord() {
return this.record;
}
private void loadFields() {
if (SOBJECT_TYPE_TO_ALL_FIELDS.containsKey(this.sobjectType) && SOBJECT_TYPE_TO_REQUIRED_FIELDS.containsKey(this.sobjectType)) {
return;
}
SOBJECT_TYPE_TO_ALL_FIELDS.put(this.sobjectType, new List<Schema.SObjectField>());
SOBJECT_TYPE_TO_REQUIRED_FIELDS.put(this.sobjectType, new List<Schema.SObjectField>());
for (Schema.SObjectField field : this.sobjectType.getDescribe().fields.getMap().values()) {
if (field.getDescribe().isCreateable() == false) {
continue;
}
SOBJECT_TYPE_TO_ALL_FIELDS.get(this.sobjectType).add(field);
if (field.getDescribe().isNillable() == false) {
// If a field is not nillable & it is createable, then it's required
SOBJECT_TYPE_TO_REQUIRED_FIELDS.get(this.sobjectType).add(field);
}
}
}
private void setUnpopulatedFieldsOnRecord(List<Schema.SObjectField> fields) {
Map<String, Object> populatedFields = this.record.getPopulatedFieldsAsMap();
for (Schema.SObjectField field : fields) {
Schema.DescribeFieldResult fieldDescribe = field.getDescribe();
if (fieldDescribe.isUpdateable() == false && fieldDescribe.isCustom() == false) {
continue;
}
// If a field was already populated by using the constructor 'TestDataFactory(SObject record)', then don't change it
// The exception is booleans, because they'll be populated with their default values.
// (Note: this^ coooould cause issues in some tests later, possibly. But for the moment, all tests are working as expected.)
if (populatedFields.containsKey(fieldDescribe.getName()) && fieldDescribe.getSoapType() != Schema.SoapType.BOOLEAN) {
continue;
}
Object fieldValue;
if (fieldDescribe.getSoapType() == Schema.SoapType.BOOLEAN) {
// For boolean fields, invert the default value as a way to know that the
// the value was set, instead of the platform using the default value
Boolean defaultValue = (Boolean) fieldDescribe.getDefaultValue();
// Several standard fields on User (and possibly other standard objects/fields?)
// actually return null for their default value - this is known, in technical terms,
// as "absolutely ridiculous", and I hate it. So, here's a silly extra null check for those fields.
fieldValue = defaultValue == null ? true : !defaultValue;
} else if (fieldDescribe.getDefaultValue() != null) {
// If there is a default value setup for the field, use it
fieldValue = fieldDescribe.getDefaultValue();
} else {
// Otherwise, we'll generate our own test value to use, based on the field's metadata
fieldValue = this.getTestValue(fieldDescribe);
}
// If we now have a value to use, set it on the record
if (fieldValue != null) {
this.record.put(field, fieldValue);
}
}
}
private Object getTestValue(Schema.DescribeFieldResult fieldDescribe) {
// Since Apex does not support case statements, we use several ugly IF-ELSE statements
// Some more complex data types, like ID & Reference, require other objects to be created
// This implementation delegates that responsibility to the test classes since DML is required to get a valid ID,
// but the logic below could be updated to support creating parent objects if needed
// Unsupported display types have been commented-out below
/*
Schema.DisplayType.Address, Schema.DisplayType.AnyType, Schema.DisplayType.Base64,
Schema.DisplayType.DataCategoryGroupReference, Schema.DisplayType.Id, Schema.DisplayType.Reference
*/
switch on fieldDescribe.getType() {
when Boolean {
return false;
}
when Combobox {
return this.getStringValue(fieldDescribe);
}
when Currency {
return (19.85).setScale(fieldDescribe.getScale());
}
when Date {
return System.today();
}
when Datetime {
return System.now();
}
when Double {
return (3.14).setScale(fieldDescribe.getScale());
}
when Email {
return 'test@example.com';
}
when EncryptedString {
return this.getStringValue(fieldDescribe);
}
when Integer {
return 1;
}
when Long {
return 1234567890L;
}
when MultiPicklist {
return fieldDescribe.getPicklistValues().get(0).getValue();
}
when Percent {
return (0.42).setScale(fieldDescribe.getScale());
}
when Phone {
return '+34 999 11 22 33';
}
when Picklist {
return fieldDescribe.getPicklistValues().get(0).getValue();
}
when String {
return this.getStringValue(fieldDescribe);
}
when TextArea {
return this.getStringValue(fieldDescribe);
}
when Time {
return Time.newInstance(13, 30, 6, 20);
}
when Url {
return 'https://salesforce.com';
}
when else {
// Any non-supported display types will return null - test classes will need to handle setting the values
return null;
}
}