Last active
June 29, 2024 21:37
-
-
Save surajp/3b516384bc6278ba565b78208bbc14ad to your computer and use it in GitHub Desktop.
Anonymous apex to create test suite
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
class Membership { | |
Id apexClassId; | |
Id apexTestSuiteId; | |
public Membership(Id suiteId, Id classId) { | |
this.apexTestSuiteId = suiteId; | |
this.apexClassId = classId; | |
} | |
} | |
String suiteName = 'My_Test_Suite'; | |
List<String> classNames = 'MyClassOneTest,MyClassTwoTest'.split(','); | |
List<ApexClass> classes = [SELECT Id, Name FROM ApexClass WHERE Name = :classNames]; | |
if (classes.size() < classNames.size()) { | |
Set<String> classSet = new Set<String>(); | |
List<String> invalidNames = new List<String>(); | |
for (ApexClass clz : classes) { | |
classSet.add(clz.Name.toLowerCase()); | |
} | |
for (String clz : classNames) { | |
if (!classset.contains(clz.toLowerCase())) { | |
invalidNames.add(clz); | |
} | |
} | |
throw new CalloutException('One or more class names may be misspelled ' + String.join(invalidNames, ',')); | |
} | |
// Id suiteId = '05FOy0000004b5pMAA'; | |
HttpRequest request = new HttpRequest(); | |
Http sender = new Http(); | |
request.setHeader('Authorization', 'Bearer ' + UserInfo.getSessionID()); | |
request.setHeader('Content-Type', 'application/json'); | |
request.setMethod('POST'); | |
request.setEndpoint(URL.getOrgDomainUrl() + '/services/data/v61.0/tooling/sobjects/ApexTestSuite/'); | |
request.setBody('{"TestSuiteName": "' + suiteName + '"}'); | |
HttpResponse resp = sender.send(request); | |
if (resp.getStatusCode() >= 300) { | |
throw new CalloutException('Somethign went wrong ' + resp.getStatusCode() + ' ' + resp.getBody()); | |
} | |
Map<String, Object> results = (Map<String, Object>) JSON.deserializeUntyped(resp.getBody()); | |
if ((Boolean) results.get('success') == false) { | |
throw new CalloutException('Somethign went wrong ' + resp.getBody()); | |
} | |
Id suiteId = (Id) results.get('id'); | |
request.setEndpoint(URL.getOrgDomainUrl() + '/services/data/v61.0/tooling/sobjects/TestSuiteMembership/'); | |
for (ApexClass clz : classes) { | |
Membership m = new Membership(suiteId, clz.Id); | |
request.setBody(JSON.serialize(m)); | |
resp = sender.send(request); | |
if (resp.getStatusCode() >= 300) { | |
throw new CalloutException('Somethign went wrong ' + resp.getStatusCode() + ' ' + resp.getBody()); | |
} | |
results = (Map<String, Object>) JSON.deserializeUntyped(resp.getBody()); | |
if ((Boolean) results.get('success') == false) { | |
throw new CalloutException('Somethign went wrong ' + resp.getBody()); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment