0% found this document useful (0 votes)
24 views24 pages

3.3 - Programmatic Sharing - Unit Tests For Programmatic Apex Sharing

The document discusses unit testing for programmatic Apex sharing. It covers test classes and methods in Apex, System.Assert methods, and the Test.startTest and Test.stopTest methods for separating governor limits during testing. The System.runAs method is also described for changing the user context during tests.
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)
24 views24 pages

3.3 - Programmatic Sharing - Unit Tests For Programmatic Apex Sharing

The document discusses unit testing for programmatic Apex sharing. It covers test classes and methods in Apex, System.Assert methods, and the Test.startTest and Test.stopTest methods for separating governor limits during testing. The System.runAs method is also described for changing the user context during tests.
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
You are on page 1/ 24

3- Programmatic Sharing

Unit Tests for Programmatic Apex Sharing

Copyright © Walid El Horr 1


Unit Tests for Programmatic Apex Sharing
• Topics covered in this lecture:

• Test Classes in Apex

• System.Assert() Methods

• Test.startTest() and Test.stopTest() Methods

• System.runAs() Method

Copyright © Walid El Horr 2


Testing
Testing your work is crucial! It is done to:

• Make sure that there are no errors

• Make sure that the expected output is working as expected as per the code specs

• Be able to deploy into the Production environment! You cannot deploy your code to Production unless tested!

Copyright © Walid El Horr 3


Testing

Testing can be performed:

• Manually through the User Interface: important, but testing through the user interface is prone to errors, and will
not catch all of the use cases for your application.

• Automatically through Unit Tests: special classes and methods that are made for testing only, and that automate
the testing procedure

Unit tests are class methods that verify In Salesforce, Testing is REQUIRED for
whether a piece of code is working Deployment to Production environment!
properly.
Think of a test method as 'Apex code
that tests other Apex code.'

Copyright © Walid El Horr 4


Testing Requirement for Deployment
• In addition to being critical for quality assurance, Apex unit tests are required for deploying and distributing Apex

Why!?

• Salesforce runs in a multitenant environment, many orgs share the same instance

• For that, any Apex code should be tested before being deployed

• Apex code can only be written in a sandbox environment or a Developer org, not in production

• After being developed in a Sandbox or Developer environment, Apex code:

• Can be deployed to a production org

• Can be made into packages and distributed via the AppExchange

Copyright © Walid El Horr 5


Testing Requirement for Deployment

In order to be able to deploy Apex to Production, or to the AppExchange:

• At least 75% of your entire Salesforce Organization Apex code must be covered by Unit Tests

• When deploying to Production, each Unit Test in your Org, is executed!

• Calls to System.debug are not counted as part of Apex code coverage

• Test methods and test classes are not counted as part of Apex code coverage

Copyright © Walid El Horr 6


Testing Requirement for Deployment

In order to be able to deploy Apex to Production, or to the AppExchange:

• Each unit test must pass

• Each trigger must have some coverage

Code coverage is calculated by dividing


the number of unique Apex code lines
executed during your test method
execution by the total number of Apex
code lines in all of your trigger and
classes.

Copyright © Walid El Horr 7


Testing Framework

There are many ways to execute Unit Tests:

• Via the Setup Page

• Apex Test Execution page

• Apex Classes page list – Run All Tests

• Specific Apex Class – Run a specific Test

• Via the Developer Console

• IDEs like VS Code

Copyright © Walid El Horr 8


Apex Unit Test
• A Method contained in Classes called Test Class which are specifically created for that purpose

• Don’t commit any data to the database

• Don’t send any emails

• Are always flagged with keyword testMethod or @isTest annotation at the method definition level

• Must always be defined in a test class. This test class should be annotated with @isTest annotation

• Are always defined as static methods

• Test methods take no arguments

Copyright © Walid El Horr 9


Apex Unit Test Syntax
• In the examples here, myTestClass is the test class which is annotated with @isTest annotation,

• Its methods can be created with either of these syntaxes:

• testMethod

• @isTest

@isTest @isTest
Public class myTestClass { Public class myTestClass {
static testMethod void myTest() { @isTest
// code_block static void myTest() {
} // code_block
} }
}

Copyright © Walid El Horr 10


System Assert Methods
• Until now, we have just covered the Apex Code coverage with testing

• We still did not compare the actual result with the expected result!

• It’s very important to test for different inputs to ensure the quality of your code

• Use System Assert methods!

Copyright © Walid El Horr 11


System Assert Methods
• There are 3 Assert methods in the System Class:

Method Description
System.assert(condition, [msg] ) • Asserts that the specified condition is true.
• If it is not, error is returned that causes code execution to halt.
• Can take optional error message as extra argument
System.assertEquals • Asserts that the first two arguments (expected and actual) are the same.
(expected, actual, [msg] ) • If they are not, error is returned that causes code execution to stop
• Can take optional error message as extra argument
System.assertNotEquals • Asserts that the first two arguments (expected and actual) are different.
(expected, actual, [msg] ) • If they are the same, error is returned that causes code execution to stop
• Can take optional error message as extra argument

Copyright © Walid El Horr 12


System Assert Methods
• Use the System Assert Methods to verify as many possible scenarios and use cases as possible

• Positive test case

• Negative test case

Copyright © Walid El Horr 13


Test.startTest and Test.stopTest System Methods
• Test.startTest and Test.stopTest, are system static methods provided by Apex

• These methods will separate the Governor Limits and will give a new fresh Governor Limit set right before Test execution

Copyright © Walid El Horr 14


Test.startTest and Test.stopTest System Methods

Test.startTest Test.stopTest

• Marks the point in your code when your test begins • Marks the point in your code when your test ends

• Used in conjunction with the stopTest method • Used in conjunction with the startTest method

• Each test method is allowed to call it only once • Each test method is allowed to call it only once

• After you call this method, you get a fresh set of


governor limits for the remainder of the test until
you call Test.stopTest

• Code before this method should be used to


initialize variables, populate data structures etc…

Copyright © Walid El Horr 15


System.runAs() Method
• The system method runAs enables you to write test methods that change the user context to an existing user or a
new user so that the user’s record sharing is enforced.

• The runAs method does NOT enforce user permissions or field-level permissions, only record sharing.

• You can use runAs only in test methods.

• The original system context is started again after all runAs test methods complete

• The runAs method ignores user license limits

• You can create new users with runAs even if your organization has no additional user licenses

Copyright © Walid El Horr 16


System.runAs() Method Example
runAs Test Class
@isTest
private class TestRunAs {
@isTest
public static void testRunAs() {
// Setup test data. This code runs as the system user.
String uniqueUserName = 'standarduser' + DateTime.now().getTime() + '@testorg.com';
Profile p = [SELECT Id FROM Profile WHERE Name='Standard User'];
User u = new User(Alias = 'standt', Email='[email protected]',
EmailEncodingKey='UTF-8', LastName='Testing', LanguageLocaleKey='en_US', LocaleSidKey='en_US', ProfileId = p.Id,
TimeZoneSidKey='America/Los_Angeles', UserName=uniqueUserName);

System.runAs(u) { // The following code runs as user 'u'


System.debug('Current User: ' + UserInfo.getUserName());
System.debug('Current Profile: ' + UserInfo.getProfileId());
}
}
}

Copyright © Walid El Horr 17


Test Class Example – Sharing Class
Sharing Class

public class InvoiceSharing {


public static void manualShareRead(Id recordId, Id userOrGroupId){
Invoice__Share invShr = new Invoice__Share();
invShr.ParentId = recordId;
invShr.UserOrGroupId = userOrGroupId;
invShr.AccessLevel = 'Read';
invShr.RowCause = Schema.Invoice__Share.RowCause.Apex__c; //created in Classic
insert invShr;
}
}

Copyright © Walid El Horr 18


Test Class Example – Test Class part 1
Sharing Test Class – part 1
@isTest
private class InvoiceSharingTest {
@isTest
static void testManualShareRead(){
List<User> users = [SELECT Id FROM User WHERE IsActive = true LIMIT 3];
Id User0Id = users[0].Id; // Owner
Id User1Id = users[1].Id; // Shared with
Id User2Id = users[2].Id; // No Access
// Create new job.
Invoice__c inv = new Invoice__c();
inv.Description__c = 'INV1';
inv.OwnerId = user0Id;
insert inv;

Test.startTest();
InvoiceSharing.manualShareRead(inv.Id, user1Id);
Test.stopTest();

Copyright © Walid El Horr 19
Test Class Example – Test Class part 2
Sharing Test Class – part 2

List<Invoice__Share> invShrs = [
SELECT Id, UserOrGroupId, AccessLevel, RowCause
FROM Invoice__Share
WHERE ParentId = :inv.Id AND UserOrGroupId= :user1Id
];

// Test for only one manual share on job.


System.assertEquals(invShrs.size(), 1, 'Set the object\'s sharing model to Private.');

// Test attributes of manual share.


System.assertEquals(invShrs[0].AccessLevel, 'Read');
System.assertEquals(invShrs[0].RowCause, 'Apex__c');
System.assertEquals(invShrs[0].UserOrGroupId, user1Id);

Copyright © Walid El Horr 20


Test Class Example – Test Class part 3
Sharing Test Class – part 3

System.runAs(users[0]) { // Invoice owner
Integer user0Inv = [SELECT count() FROM Invoice__c];
System.assertEquals(1, user0Inv);
System.debug('user0Inv: ' +user0Inv);
}
System.runAs(users[1]) { // Invoice shared as Read
Integer user1Inv = [SELECT count() FROM Invoice__c];
System.assertEquals(1, user1Inv);
System.debug('user1Inv: ' +user1Inv);
}
System.runAs(users[2]) { // No access to the Invoice
Integer user2Inv = [SELECT count() FROM Invoice__c];
System.assertEquals(0, user2Inv);
System.debug('user2Inv: ' +user2Inv);
}
}
}
Copyright © Walid El Horr 21
Demo

Demo

Unit Tests for


Apex Sharing

22
Summary - Unit Tests for Programmatic Apex Sharing
Subject Description

Testing Important to check the configuration made


Unit Test - Class methods that verify whether a piece of code is working properly.
- Apex code that tests other Apex code
Testing Requirement for - 75% code coverage
Deployment - Each unit test must pass
- Each trigger must have some coverage
Testing Framework - Setup menu
- Developer Console
- IDE
Annotations Apex class requires the @isTest annotation
Apex Unit Test (test method) requires either @isTest or testMethod
System Assert Methods Used to check the class output as opposed to only performing code copverage
Test.startTest and Test.stopTest Will give a new fresh Governor Limit set right before Test execution
System.runAs() - Changes the current user to the specified user, and execute the test as this user
- Check record access (N/A for permissions and FLS)

Copyright © Walid El Horr 23


Unit Tests for Programmatic Apex Sharing

Thanks for Watching! ☺

Copyright © Walid El Horr 24

You might also like