0% found this document useful (0 votes)
184 views36 pages

Salesforce Apex Triggers - Coding and Testing

Uploaded by

raj yadav
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
184 views36 pages

Salesforce Apex Triggers - Coding and Testing

Uploaded by

raj yadav
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Apex Triggers :

[Link]
lazerconnect&trailmix_slug=salesforce-developer-catalyst

1) Get Started with Apex Trigger

AccountAddressTrigger Code :

trigger AccountAddressTrigger on Account (before insert, before update) {


for (Account a : [Link]) {
if (a.Match_Billing_Address__c == TRUE){
[Link] = [Link];
}
}
}

2) Bulk Apex Triggers Unit

ClosedOpportunityTrigger Code :

trigger ClosedOpportunityTrigger on Opportunity (after insert,


after update) {
List<Task> taskList = new List<Task>();

for (Opportunity o :[SELECT Id,Name FROM Opportunity


WHERE Id IN :[Link]]){
[Link](new Task(Subject='Follow Up Test Task',
WhatId=[Link],
Status='Not Started',
Priority='Normal'));
}
if ([Link]() > 0){
insert taskList;
}
}
Apex Testing :
[Link]
ing?trailmix_creator_id=trailblazerconnect&trailmix_slug=salesfo
rce-developer-catalyst

1)Get Started with Apex Unit Testing

VerifyDate Code :

public class VerifyDate {

//method to handle potential checks against two dates


public static Date CheckDates(Date date1, Date date2) {
//if date2 is within the next 30 days of date1, use
date2. Otherwise use the end of the month
if(DateWithin30Days(date1,date2)) {
return date2;
} else {
return SetEndOfMonthDate(date1);
}
}

//method to check if date2 is within the next 30 days of


date1
private static Boolean DateWithin30Days(Date date1, Date
date2) {
//check for date2 being in the past
if( date2 < date1) { return false; }

//check that date2 is within (>=) 30 days of date1


Date date30Days = [Link](30); //create a date 30
days away from date1
if( date2 >= date30Days ) { return false; }
else { return true; }
}
//method to return the end of the month of a given date
private static Date SetEndOfMonthDate(Date date1) {
Integer totalDays = [Link]([Link](),
[Link]());
Date lastDay = [Link]([Link](),
[Link](), totalDays);
return lastDay;
}

TestVerifyDate Code :

@isTest
private class TestVerifyDate {

@isTest static void testCheckDates() {


Date now = [Link]();
Date lastOfTheMonth = [Link]([Link](),
[Link](), [Link]([Link](), [Link]()));
Date plus60 = [Link]().addDays(60);

Date d1 = [Link](now, now);


[Link](now, d1);

Date d2 = [Link](now, plus60);


[Link](lastOfTheMonth, d2);
}

2) Test Apex Triggers Unit

RestrictContactByName Code :

trigger RestrictContactByName on Contact (before insert, before


update) {
//check contacts prior to insert or update for invalid data
For (Contact c : [Link]) {
if([Link] == 'INVALIDNAME') { //invalidname is
invalid
[Link]('The Last Name "'+[Link]+'" is not
allowed for DML');
}

TestRestrictContactByName Code :

@isTest
private class TestRestrictContactByName {

@isTest
static void invalidName() {
try {
Contact c = new Contact(LastName='INVALIDNAME');
insert c;
}
catch (Exception e) {
[Link](true);
}
}

3) Create Test Data for Apex Tests :

RandomContactFactory Code :
public class RandomContactFactory {

public static List<Contact> generateRandomContacts(Integer


num, String lastName) {
List<Contact> contacts = new List<Contact>();
for (Integer i = 0; i < num; i++) {
Contact c = new Contact(FirstName=[Link](),
LastName=lastName);
[Link](c);
}
return contacts;
}

Asynchronous Apex :
[Link]
=trailblazerconnect&trailmix_slug=salesforce-developer-catalyst

1)Quiz
2)Use Future Methods

AccountProcessor Code :

public class AccountProcessor {


@future
public static void countContacts(List<Id> accountIds) {
List<Account> accounts = [SELECT Id,
Name,
Number_of_Contacts__c,
(
SELECT [Link]
FROM Contacts
)
FROM Account
WHERE Id in :accountIds];
for (Account a : accounts) {
a.Number_of_Contacts__c = [Link]();
}
update accounts;
}
}

AccountProcessorTest Code :

@isTest
private class AccountProcessorTest {

static TestMethod void myTest() {


List<Account> accounts = new List<Account>();
for (Integer i=0; i<100; i++) {
Account account = new Account();
[Link] = 'AccountProcessorTest Account ' + i;
[Link](account);
}
insert accounts;

List<Id> accountIds = new List<Id>();


List<Contact> contacts = new List<Contact>();
for (Account a : accounts) {
[Link]([Link]);
for (Integer i=0; i<5; i++) {
Contact contact = new Contact();
[Link] = 'AccountProcessor Test
Contact';
[Link] = [Link](i);
[Link] = [Link];
[Link](contact);
}
}
insert contacts;
[Link]();
[Link](accountIds);
[Link]();

List<Account> results = [SELECT Id,


Number_of_Contacts__c
FROM Account
WHERE Id in :accountIds];
for (Account a : results) {
[Link](5, a.Number_of_Contacts__c);
}
}
}

3)Use Batch Apex

LeadProcessor Code :

global class LeadProcessor implements


[Link]<sObject>, [Link] {

global Integer recs_processed = 0;

global [Link] start([Link]


bc) {
String sQuery = '';
sQuery += 'SELECT Id, Name, Status,';
sQuery += 'LeadSource ';
sQuery += 'FROM Lead ';
sQuery += 'LIMIT 100000';
return [Link](sQuery);
}

global void execute([Link] bc, List<Lead>


scope) {
for (Lead l : scope) {
[Link] = 'Dreamforce';
recs_processed += 1;
}
update scope;
}

global void finish([Link] bc) {


AsyncApexJob job = [SELECT Id,
Status,
NumberOfErrors,
TotalJobItems,
JobItemsProcessed,
[Link]
FROM AsyncApexJob
WHERE Id = :[Link]()];
String s = '';
s += [Link] + ' job items processed ';
s += 'out of ' + [Link] + ' total job items.
';
s += [Link] + ' error(s) encountered. ';
[Link](s);
s = recs_processed + ' record(s) processed.';
[Link](s);
}
}

LeadProcessorTest Code :

@isTest
private class LeadProcessorTest {

@testSetup
static void createLeads() {
List<Lead> leads = new List<Lead>();
for (Integer i=0; i<200; i++) {
Lead l = new Lead();
[Link] = 'Test';
[Link] = 'Lead';
[Link] = 'Test Lead ' + i;
[Link](l);
}
insert leads;
}

static TestMethod void myTest() {


[Link]();
LeadProcessor lp = new LeadProcessor();
Id batchId = [Link](lp);
[Link]();

[Link](200, [SELECT Count()


FROM Lead
WHERE Name = 'Test Lead'
AND LeadSource =
'Dreamforce']);
}
}

4)Controp Processes with Queueable Apex

AddPrimaryContact Code :

public class AddPrimaryContact implements Queueable {

private Contact contactObj;


private String state_code;

public AddPrimaryContact(Contact c, String s) {


[Link] = c;
this.state_code = s;
}

public void execute(QueueableContext context) {


List<Account> accounts = [SELECT Id
FROM Account
WHERE BillingState =
:this.state_code
LIMIT 200];

List<Contact> contacts = new List<Contact>();


for (Account a : accounts) {
Contact c = [Link](false, false,
false, false);
[Link] = [Link];
[Link](c);
}

if ([Link]() > 0) {
insert contacts;
}
}
}

AddPrimaryContactTest Code :

@isTest
private class AddPrimaryContactTest {
@testSetup
static void setup() {
List<Account> accounts = new List<Account>();
for (Integer i=0; i<50; i++) {
Account ny = new Account();
[Link] = 'Test Account (NY)';
[Link] = 'NY';
[Link](ny);
Account ca = new Account();
[Link] = 'Test Account (CA)';
[Link] = 'CA';
[Link](ca);
}
insert accounts;
}
static TestMethod void myTest() {
Contact contactObj = new Contact(
FirstName = 'California',
LastName = 'Bob'
);
String state_abbrev = 'CA';

[Link]();
AddPrimaryContact apc = new
AddPrimaryContact(contactObj, state_abbrev);
Id jobId = [Link](apc);
[Link]();

List<Account> accounts = [SELECT Id, (SELECT


[Link] FROM [Link]) FROM Account WHERE
BillingState = 'CA'];
[Link](50, [Link]());
for (Account a : accounts) {
[Link]([Link](), 1);
}
}
}

5)Schedule Jobs Using the Apex Scheduler

DailyLeadProcessor Code :

global class DailyLeadProcessor implements Schedulable {

global void execute(SchedulableContext ctx) {


List<Lead> leads = [SELECT Id,
LeadSource
FROM Lead
WHERE LeadSource = '' OR LeadSource =
null
LIMIT 200];
for (Lead l : leads) {
[Link] = 'Dreamforce';
}

if ([Link]() > 0) {
update leads;
}
}
}

DailyLeadProcessorTest Code :

@isTest
private class DailyLeadProcessorTest {

@testSetup
static void setup() {
List<Lead> leads = new List<Lead>();
for (Integer i=0; i<200; i++) {
Lead l = new Lead();
[Link] = 'Test';
[Link] = 'Lead ' + i;
[Link] = 'Test Company ' + i;
[Link](l);
}
insert leads;
}

static TestMethod void myTest() {


String jobName = 'Daily Lead Processor - Test';
String CRON_EXP = '0 0 0 15 3 ? 2017'; // dummy cron
entry

[Link]();
DailyLeadProcessor dp = new DailyLeadProcessor();
String JobId = [Link](jobName, CRON_EXP, dp);
[Link]();

List<Lead> results = [SELECT Id FROM Lead WHERE


LeadSource = 'Dreamforce'];
[Link](200, [Link]());
}
}

Apex Integration Services


:[Link]
egration_services?trailmix_creator_id=trailblazerconnect&trailmi
x_slug=salesforce-developer-catalyst

1)Quiz
2)Apex REST Callouts

AnimalLocator Code :

public class AnimalLocator {

public static HttpResponse makeGetCallout {


Http http = new Http();
HttpRequest request = new HttpRequest();
[Link]('[Link]
[Link]/animals/:id');
[Link]('GET');
HttpResponse response = [Link](request);
// If the request is successful, parse the JSON response.
if ([Link]() == 200) {
// Deserialize the JSON string into collections of
primitive data types.
Map<Integer, Object> Results
}
}
}

AnimalLocatorTest Code :

@isTest
private class AnimalLocatorTest{
@isTest static void AnimalLocatorMock1() {
[Link]([Link], new AnimalLocatorMock());
string result=[Link](3);
string expectedResult='chicken';
[Link](result, expectedResult);
}
}

AnimalLocatorMock Code :

@isTest
global class AnimalLocatorMock implements HttpCalloutMock {
global HTTPResponse respond(HTTPRequest request) {
HttpResponse response = new HttpResponse();
[Link]('Content-Type', 'application/json');

[Link]('{"animal":{"id":1,"name":"chicken","eats":"chicken
food","says":"cluck cluck"}}');
[Link](200);
return response;
}
}

2)Apex SOAP Callouts

ParkService Code :

//Generated by wsdl2apex
public class ParkService {

public class byCountryResponse {

public String[] return_x;

private String[] return_x_type_info = new


String[]{'return','[Link]
1','false'};

private String[] apex_schema_type_info = new


String[]{'[Link]

private String[] field_order_type_info = new


String[]{'return_x'};

public class byCountry {

public String arg0;

private String[] arg0_type_info = new


String[]{'arg0','[Link]

private String[] apex_schema_type_info = new


String[]{'[Link]

private String[] field_order_type_info = new


String[]{'arg0'};

public class ParksImplPort {

public String endpoint_x = '[Link]


[Link]/service/parks';

public Map<String,String> inputHttpHeaders_x;


public Map<String,String> outputHttpHeaders_x;

public String clientCertName_x;

public String clientCert_x;

public String clientCertPasswd_x;

public Integer timeout_x;

private String[] ns_map_type_info = new


String[]{'[Link] 'ParkService'};

public String[] byCountry(String arg0) {

[Link] request_x = new


[Link]();

request_x.arg0 = arg0;

[Link] response_x;

Map<String, [Link]>
response_map_x = new Map<String,
[Link]>();

response_map_x.put('response_x', response_x);

[Link](

this,

request_x,

response_map_x,

new String[]{endpoint_x,

'',

'[Link]

'byCountry',
'[Link]

'byCountryResponse',

'[Link]'}

);

response_x = response_map_x.get('response_x');

return response_x.return_x;

ParkLocator Code :

public class ParkLocator {

public static String[] country(String country){

[Link] parks = new


[Link]();

String[] parksname = [Link](country);

return parksname;

}
ParkLocatorTest Code :

@isTest

private class ParkLocatorTest{

@isTest

static void testParkLocator() {

[Link]([Link], new
ParkServiceMock());

String[] arrayOfParks = [Link]('India');

[Link]('Park1', arrayOfParks[0]);

ParkServiceMock Code :

@isTest

global class ParkServiceMock implements WebServiceMock {

global void doInvoke(

Object stub,

Object request,

Map<String, Object> response,

String endpoint,
String soapAction,

String requestName,

String responseNS,

String responseName,

String responseType) {

[Link] response_x = new


[Link]();

List<String> lstOfDummyParks = new List<String>


{'Park1','Park2','Park3'};

response_x.return_x = lstOfDummyParks;

[Link]('response_x', response_x);

4) Apex Web Services

AccountManager Code :

@RestResource(urlMapping='/Accounts/*/contacts')
global with sharing class AccountManager {

@HttpGet
global static account getAccount() {

RestRequest request = [Link];

String accountId =
[Link]([Link]('/')-18,
[Link]('/'));
List<Account> a = [select id, name, (select id, name from
contacts) from account where id = :accountId];
List<contact> co = [select id, name from contact where
[Link] = :accountId];
[Link]('** a[0]= '+ a[0]);
return a[0];

AccountManagerTest Code :

@Istest(SeeAllData=true)
public class AccountManagerTest {

@IsTest
public static void testaccountmanager() {
RestRequest request = new RestRequest();
[Link] = '[Link]
[Link]/services/apexrest/Accounts/00190000016cw4tAAA/con
tacts';
[Link] = 'GET';
[Link] = request;

[Link]('test account result = '+


[Link]());

APEX SPECIALIST SUPERBADGE :


[Link]
n_services?trailmix_creator_id=trailblazerconnect&trailmix_slug=salesf
orce-developer-catalyst

1)Quiz

2)Automate Record Creation

MaintenanceRequestHelper Code :

public with sharing class MaintenanceRequestHelper {

public static void updateworkOrders(List<Case>


updWorkOrders, Map<Id,Case> nonUpdCaseMap) {

Set<Id> validIds = new Set<Id>();

For (Case c : updWorkOrders){

if ([Link]([Link]).Status != 'Closed' &&


[Link] == 'Closed'){

if ([Link] == 'Repair' || [Link] == 'Routine


Maintenance'){

[Link]([Link]);

}
if (![Link]()){

List<Case> newCases = new List<Case>();

Map<Id,Case> closedCasesM = new Map<Id,Case>([SELECT


Id, Vehicle__c, Equipment__c,
Equipment__r.Maintenance_Cycle__c,(SELECT
Id,Equipment__c,Quantity__c FROM Equipment_Maintenance_Items__r)

FROM
Case WHERE Id IN :validIds]);

Map<Id,Decimal> maintenanceCycles = new


Map<ID,Decimal>();

AggregateResult[] results = [SELECT


Maintenance_Request__c,
MIN(Equipment__r.Maintenance_Cycle__c)cycle FROM
Equipment_Maintenance_Item__c WHERE Maintenance_Request__c IN
:ValidIds GROUP BY Maintenance_Request__c];

for (AggregateResult ar : results){

[Link]((Id)
[Link]('Maintenance_Request__c'), (Decimal) [Link]('cycle'));

for(Case cc : [Link]()){

Case nc = new Case (

ParentId = [Link],

Status = 'New',
Subject = 'Routine Maintenance',

Type = 'Routine Maintenance',

Vehicle__c = cc.Vehicle__c,

Equipment__c =cc.Equipment__c,

Origin = 'Web',

Date_Reported__c = [Link]()

);

If ([Link]([Link])){

nc.Date_Due__c =
[Link]().addDays((Integer) [Link]([Link]));

[Link](nc);

insert newCases;

List<Equipment_Maintenance_Item__c> clonedWPs = new


List<Equipment_Maintenance_Item__c>();

for (Case nc : newCases){

for (Equipment_Maintenance_Item__c wp :
[Link]([Link]).Equipment_Maintenance_Items__r){

Equipment_Maintenance_Item__c wpClone =
[Link]();

wpClone.Maintenance_Request__c = [Link];

[Link](wpClone);

insert ClonedWPs;

MaitenanceRequest Code :
trigger MaintenanceRequest on Case (before update, after update)
{
if([Link] && [Link]){
[Link]([Link],
[Link]);
}
}

3)Synchronize Salesforce Data


WarehouseCalloutService Code :

public with sharing class WarehouseCalloutService {

private static final String WAREHOUSE_URL = '[Link]


[Link]/equipment';

//@future(callout=true)
public static void runWarehouseEquipmentSync(){

Http http = new Http();


HttpRequest request = new HttpRequest();

[Link](WAREHOUSE_URL);
[Link]('GET');
HttpResponse response = [Link](request);

List<Product2> warehouseEq = new List<Product2>();

if ([Link]() == 200){
List<Object> jsonResponse =
(List<Object>)[Link]([Link]());
[Link]([Link]());

for (Object eq : jsonResponse){


Map<String,Object> mapJson =
(Map<String,Object>)eq;
Product2 myEq = new Product2();
myEq.Replacement_Part__c = (Boolean)
[Link]('replacement');
[Link] = (String) [Link]('name');
myEq.Maintenance_Cycle__c = (Integer)
[Link]('maintenanceperiod');
myEq.Lifespan_Months__c = (Integer)
[Link]('lifespan');
myEq.Cost__c = (Decimal)
[Link]('lifespan');
myEq.Warehouse_SKU__c = (String)
[Link]('sku');
myEq.Current_Inventory__c = (Double)
[Link]('quantity');
[Link](myEq);
}

if ([Link]() > 0){


upsert warehouseEq;
[Link]('Your equipment was synced with the
warehouse one');
[Link](warehouseEq);
}

}
}
}

4)Schedule Synchronization

WarehouseSyncSchedule Code :

global class WarehouseSyncSchedule implements Schedulable {


global void execute(SchedulableContext ctx) {

[Link]();
}
}
5)Test Automatic Logic
MaintenanceRequestHelperTest Code :

@istest
public with sharing class MaintenanceRequestHelperTest {

private static final string STATUS_NEW = 'New';


private static final string WORKING = 'Working';
private static final string CLOSED = 'Closed';
private static final string REPAIR = 'Repair';
private static final string REQUEST_ORIGIN = 'Web';
private static final string REQUEST_TYPE = 'Routine
Maintenance';
private static final string REQUEST_SUBJECT = 'Testing
subject';

PRIVATE STATIC Vehicle__c createVehicle(){


Vehicle__c Vehicle = new Vehicle__C(name =
'SuperTruck');
return Vehicle;
}

PRIVATE STATIC Product2 createEq(){


product2 equipment = new product2(name =
'SuperEquipment',
lifespan_months__C =
10,
maintenance_cycle__C =
10,
replacement_part__c =
true);
return equipment;
}

PRIVATE STATIC Case createMaintenanceRequest(id vehicleId,


id equipmentId){
case cs = new case(Type=REPAIR,
Status=STATUS_NEW,
Origin=REQUEST_ORIGIN,
Subject=REQUEST_SUBJECT,
Equipment__c=equipmentId,
Vehicle__c=vehicleId);
return cs;
}

PRIVATE STATIC Equipment_Maintenance_Item__c


createWorkPart(id equipmentId,id requestId){
Equipment_Maintenance_Item__c wp = new
Equipment_Maintenance_Item__c(Equipment__c = equipmentId,

Maintenance_Request__c = requestId);
return wp;
}

MaintenanceRequestHelper Code :

public with sharing class MaintenanceRequestHelper {


public static void updateworkOrders(List<Case>
updWorkOrders, Map<Id,Case> nonUpdCaseMap) {
Set<Id> validIds = new Set<Id>();

For (Case c : updWorkOrders){


if ([Link]([Link]).Status != 'Closed' &&
[Link] == 'Closed'){
if ([Link] == 'Repair' || [Link] == 'Routine
Maintenance'){
[Link]([Link]);

}
}
}
if (![Link]()){
List<Case> newCases = new List<Case>();
Map<Id,Case> closedCasesM = new Map<Id,Case>([SELECT
Id, Vehicle__c, Equipment__c,
Equipment__r.Maintenance_Cycle__c,(SELECT
Id,Equipment__c,Quantity__c FROM Equipment_Maintenance_Items__r)
FROM
Case WHERE Id IN :validIds]);
Map<Id,Decimal> maintenanceCycles = new
Map<ID,Decimal>();
AggregateResult[] results = [SELECT
Maintenance_Request__c,
MIN(Equipment__r.Maintenance_Cycle__c)cycle FROM
Equipment_Maintenance_Item__c WHERE Maintenance_Request__c IN
:ValidIds GROUP BY Maintenance_Request__c];

for (AggregateResult ar : results){


[Link]((Id)
[Link]('Maintenance_Request__c'), (Decimal) [Link]('cycle'));
}

for(Case cc : [Link]()){
Case nc = new Case (
ParentId = [Link],
Status = 'New',
Subject = 'Routine Maintenance',
Type = 'Routine Maintenance',
Vehicle__c = cc.Vehicle__c,
Equipment__c =cc.Equipment__c,
Origin = 'Web',
Date_Reported__c = [Link]()

);

If ([Link]([Link])){
nc.Date_Due__c =
[Link]().addDays((Integer) [Link]([Link]));
}

[Link](nc);
}

insert newCases;

List<Equipment_Maintenance_Item__c> clonedWPs = new


List<Equipment_Maintenance_Item__c>();
for (Case nc : newCases){
for (Equipment_Maintenance_Item__c wp :
[Link]([Link]).Equipment_Maintenance_Items__r){
Equipment_Maintenance_Item__c wpClone =
[Link]();
wpClone.Maintenance_Request__c = [Link];
[Link](wpClone);

}
}
insert ClonedWPs;
}
}
}

MaintenanceRequest Code :

trigger MaintenanceRequest on Case (before update, after update)


{
if([Link] && [Link]){
[Link]([Link],
[Link]);
}
}

6) Test Callout Logic

WarehouseCalloutService Code :
public with sharing class WarehouseCalloutService {

private static final String WAREHOUSE_URL = '[Link]


[Link]/equipment';

//@future(callout=true)
public static void runWarehouseEquipmentSync(){

Http http = new Http();


HttpRequest request = new HttpRequest();

[Link](WAREHOUSE_URL);
[Link]('GET');
HttpResponse response = [Link](request);

List<Product2> warehouseEq = new List<Product2>();

if ([Link]() == 200){
List<Object> jsonResponse =
(List<Object>)[Link]([Link]());
[Link]([Link]());

for (Object eq : jsonResponse){


Map<String,Object> mapJson =
(Map<String,Object>)eq;
Product2 myEq = new Product2();
myEq.Replacement_Part__c = (Boolean)
[Link]('replacement');
[Link] = (String) [Link]('name');
myEq.Maintenance_Cycle__c = (Integer)
[Link]('maintenanceperiod');
myEq.Lifespan_Months__c = (Integer)
[Link]('lifespan');
myEq.Cost__c = (Decimal)
[Link]('lifespan');
myEq.Warehouse_SKU__c = (String)
[Link]('sku');
myEq.Current_Inventory__c = (Double)
[Link]('quantity');
[Link](myEq);
}

if ([Link]() > 0){


upsert warehouseEq;
[Link]('Your equipment was synced with the
warehouse one');
[Link](warehouseEq);
}

}
}
}

WarehouseCalloutServiceTest Code :

@isTest

private class WarehouseCalloutServiceTest {


@isTest
static void testWareHouseCallout(){
[Link]();
// implement mock callout test here
[Link]([Link], new
WarehouseCalloutServiceMock());
[Link]();
[Link]();
[Link](1, [SELECT count() FROM Product2]);
}
}

WarehouseCalloutServiceMock Code :
@isTest
global class WarehouseCalloutServiceMock implements
HttpCalloutMock {
// implement http mock callout
global static HttpResponse respond(HttpRequest request){

[Link]('[Link]
[Link]/equipment', [Link]());
[Link]('GET', [Link]());

// Create a fake response


HttpResponse response = new HttpResponse();
[Link]('Content-Type', 'application/json');

[Link]('[{"_id":"55d66226726b611100aaf741","replacemen
t":false,"quantity":5,"name":"Generator 1000
kW","maintenanceperiod":365,"lifespan":120,"cost":5000,"sku":"10
0003"}]');
[Link](200);
return response;
}
}

7) Test Scheduling Logic

WarehouseSyncSchedule Code :

global class WarehouseSyncSchedule implements Schedulable {


global void execute(SchedulableContext ctx) {

[Link]();
}
}

WarehouseSyncScheduleTest Code :

@isTest
public class WarehouseSyncScheduleTest {

@isTest static void WarehousescheduleTest(){


String scheduleTime = '00 00 01 * * ?';
[Link]();
[Link]([Link], new
WarehouseCalloutServiceMock());
String jobID=[Link]('Warehouse Time To Schedule
to Test', scheduleTime, new WarehouseSyncSchedule());
[Link]();
//Contains schedule information for a scheduled job.
CronTrigger is similar to a cron job on UNIX systems.
// This object is available in API version 17.0 and
later.
CronTrigger a=[SELECT Id FROM CronTrigger where
NextFireTime > today];
[Link](jobID, [Link],'Schedule ');

}
}

You might also like