-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathMock.cls
78 lines (67 loc) · 2.21 KB
/
Mock.cls
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
/*
* Copyright (c) 2022, salesforce.com, inc.
* All rights reserved.
* SPDX-License-Identifier: BSD-3-Clause
* For full license text, see the LICENSE file in the repo root or https://opensource.org/licenses/BSD-3-Clause
*/
@isTest
global class Mock implements System.StubProvider {
global Object stub { get; set; }
private Map<String, MethodSpy> spies = new Map<String, MethodSpy>();
private Mock(final Type aType, final StubBuilder stubBuilder) {
this.stub = stubBuilder.build(aType, this);
}
global Object handleMethodCall(
Object stubbedObject,
String stubbedMethodName,
Type returnType,
List<Type> listOfParamTypes,
List<String> listOfParamNames,
List<Object> listOfArgs
) {
Object result;
if (this.spies.containsKey(stubbedMethodName)) {
MethodSpy spy = this.getSpy(stubbedMethodName);
result = spy.call(listOfArgs);
}
return result;
}
global MethodSpy spyOn(final String methodName) {
if (!this.spies.containsKey(methodName)) {
this.spies.put(methodName, new MethodSpy(methodName));
}
return this.getSpy(methodName);
}
global MethodSpy getSpy(final String methodName) {
return this.spies.get(methodName);
}
global static Mock forType(final Type aType) {
return Mock.forType(aType, new DefaultStubBuilder());
}
global static Mock forType(final Type aType, final StubBuilder stubBuilder) {
return new Mock(aType, stubBuilder);
}
static Integer s_num = 1;
global static String generateFakeId(Schema.SObjectType sot) {
String result = String.valueOf(s_num++);
return sot.getDescribe().getKeyPrefix() +
'0'.repeat(12 - result.length()) +
result;
}
global static Database.SaveResult generateFakeSaveResult(
Schema.SObjectType sot
) {
return (Database.SaveResult) JSON.deserialize(
'{"success":true,"id":"' + generateFakeId(sot) + '"}',
Database.SaveResult.class
);
}
global interface StubBuilder {
Object build(final Type aType, System.StubProvider stubProvider);
}
private class DefaultStubBuilder implements StubBuilder {
public Object build(final Type aType, System.StubProvider stubProvider) {
return Test.createStub(aType, stubProvider);
}
}
}