You are on page 1of 43
© FOCUSONFORCE Testing, Debugging, and Deployment: Testing Write and execute tests for triggers, controllers, classes, flows, and processes using various sources of test data. Develop your career with Salesforce Training and Certification Preparation (@ rocusovronce Table of Contents © sexiensoexcontlers © estos Governor its @ sesinePernision Set Geos © Iestine Code as Another User © seston acess © wanmasouces (@ rocusovroRce Table of Contents © ssa tstsotutor Test Data © viet cis © ssnestatcResurcesas est Data © Perccbook tet bata @ Usinefxistine Data as Test Data © fbenuetectsinDevloperConssle (@ rocusoyronce Table of Contents © feecute Tests inVisual Studio Code @ feccute Tests Using an APL @ Monazed Packages and Unlocked Packages @ dither Concents & Best Practices @ voit Test Examales (@ rocusovrorce After studying this topic, you should be able to: Identify how tonite tests for Apex code as well as flows and process Determine the cltferent options for generating test data that can beusedin test methods Define the diferent sources of test data for executingtests andlor options fr creating them Describe the diffrent tools or platforms that ean be used for executing testsin Salesforce @ centty best practices o considerations when writing unit tests in Salesforce (@ roousovronce Introduction ‘Apex testingis part ofthe application lifecycle management in Salesforce and itis a technical requirement before Apex code can be ‘ployed toa production org CP) Inthe following topics, writing tess for Apex classes, triggers, controllers, as well as tests for flows and processes willbe discussed. ‘Theeiferent sources or test data that canbe used innit tests llbe identified including the different tool that ae available for executing ‘ess. Salesforce provides arobust testing framework which makes't easy for developers to manage and run tess and facilitate in building ‘optimized, table Salesforce applications (@ rocusonrorce Apex Testing Overview oem faring scot oat STEP L WRITEUNITTESTS Write unit tests for Apex classes: b> Saipan Md i a STEP 3: GENERATE CODE COVERAGE STEP 4: CHECK TEST RESULTS —_ Generate test coverage for code Check whether tests succeed or fail every tine atestls rin Inthe Developer Console. (@ rocusovronce Application Lifecycle Management Testing Apex code is a required process in the Salesforce application lifecycle management. (@ roousoiroRce Application Lifecycle Management NOTE © ‘ter or during development unit test ane created to es application code. When development has ‘completed andl tests have passe, code canbe deployed to the production ors. (@ rocusoyroRce Writing I Init Tacte Wwrruig wie meow (@ rocusoiroRce Unit Test Overview Test Data Factory | -@ sm |) rw rset G@ Test Class Writing Unit Tests Unit tests are test methods written to verify that Apex code is working and produces the ‘expected results, ANNOTATION || TESTMETHOD TEST DATA DATA SETUP AND ACCESS: DEFINITION || REQUIREMENT METHOD, Testelassesand || Testmethodeshouldbe | | Test methods areusedto| | Testelats method methods mustbe || stale, retuen no values | | test unetionality and annotated with annotated with @isTest ‘andcanbe either privateor public. (oid and accept no | | data sotest data should | @testsetup can be used parameters be available. tosetuptest data. (6 rocusoyroRce Writing Unit Tests ‘unit test invoke the method or trigger that is being tested. If a method or trigger is not called, it will ‘also negatively impact the code coverage computation ‘TESTING METHODS The method thats being tested can be called directly fromthe test method, TESTING TRIGGERS Totest riggers. include DML operations in test methods toinvoke the triggers, lal RUNNING TESTS Peers RESULTS 1B init taste shone exociite the Anex methods or “Tost recults cheuld he verifind with the usm of ‘riggers that are being tested assert methods, (@ rocusovrorce Verifying Code Behavior Assert methods are used to verify code behavior. These methods throw an exception when the actual result does nat match the expected result. [Farmer ole ma [arecmarte Sy mie tes Wr eel 5 | sytonanersnttplsonnctets stale mel, [y.termerisenlstay Yeon, fant pet ye ——s | [strtrceaas Magee as wor oat 95 (6 FocusovroRce Anatomy of an Apex Test Class Below shows a sample typical structure of an Apex test class. (aster ee | vance teste) { , (@ rocusovrorce 1s] Structure of Unit Tests Allunit tests follow the same structure, which Is to create test data, call the test method, and then verify results, Data is not committed so it does nat need to be deleted. inuann EXECUTE METHODS VERIFY RESULTS Creat valid test data Execute the methodsto Verity the expected results tor testing. betested Using assertions (6 rocusovronce Code Coverage Computation Code Coverage Percentage, which is computed when running tests, uses the formula CCP = (number of covered lines) / (number of covered lines + number of uncovered lines) ‘does not impact code coverage state inepee macpscity = 4 percentage: = Code comments ~ Class name definition = Lines that only contain brackets + ~ system debug statements ‘Only the lines highlighted in blue 1 oad ss So whist pasomrecs are included in the code coverage i computation. (@ rocusovronce (@ rocusoyroRce Positive and Negative Cases in Test Classes Units tests should include both positive and negative test cases to verify positive and negative behavior ‘of code. POSITIVE CASE A postive test ease uses valid inputs Within the governor limits to verity that the cade behaves as expected @ | necative case Anesative test caseuses one ormore invalid inputs exceeds governor limits toverity thatthe cade does allow norma racesinginsuch conditions. (@ rocusovrorce EAxAINpIE MpER U1a> The Apex class below automaticaly creates a sales order for each Closed Won opportunity and updates a field on the opportunity STE AS ein rs Ste ts may sor ar inser the sales orders and Se cy update the opportunities (@ rocusovrorce Example Positive Test Case for Apex Class Below sample tet class for testing the behaviour ofthe class when vali input is provided oS ST a TE TTS ‘ (@ roousovronce se sales eb fas ben cee spires Example Negative Test Case for Apex Class Below sample test class for testing the behaviour of the class when invalid input is provided te cls pportnityioiaecantest le qmoge tt ate merit wp [esters geared —[ mete he etiod tt) ie en Toe er GW CIR wee a Sena (otale mate re 9) b (@ rocusovronce Example Apex Trigger ‘The Apex trigger below automatically assigns the account of a contact based on the serial number of a service level agreement rlagrcntcorggr on cntct (er ert) ¥ Usetrinods SS Inguerying the accounts on, vt NY ‘Query the accounts and create aerial umber mapping oassign tothe contact os rocusyronce a Example Unit Test for Apex Trigger {A sample test class for testing the functionality ofthe the ContctTrigger Apex trigger oy ana (@ roousovronce Testing Apex Controllers (@ rocusoyroRce 2s Unit Testing for Controllers and Controller Extensions Controller extensions and custom controllers should be covered by unit tess, QUERY PARAMETERS, roe ‘Query parameters canbe set which can then beused nthe’ (@ rocusovronce Controller Unit Test Example ‘Sample unt test that calls methods and passes parameters to testa Visualforce controller (Weify thatthe success page relter ot) ce010; isworkingas expected vss" (erty that the user was successfully created ies, seta (@ roousovronce Testing Governor Limits (@ FoousoyroRcE Testing Governor Limits Unit tests or Apex code executed in test methods are subject to governor limits © START AND STOP TEST ‘TeststartTest) and TeststopTest() methods, which can only be called ‘once in each test method, can be used in conjunction with Limits methods to test governor limits by determining the preximity of Apex EO Lk vy coger reacning tne governor mt (6 rocusoyroRce Testing Governor Limits © ACTUAL CODE TESTING ‘ThestartTest and stopTest methods markthe polnt where the testing of 1 code actully begins and ends. Code before actual est begins should be used to st up the scenario such a initializing variables and creating test data, e © FRESH GOVERNOR LIMITS pn ‘Any code executed after startest and before stopTest is assigned anew g setof governor limits. For example, evenit99 SOQ. queries were executed before stortTest, 100 additional queries can be performed after it However only 1 more, SOQL query sallowed to execute after stopTest before exceeding the SSOQL query limit (@ roousovronce Limits Methods for Testing Governor Limits Limits methods is used to return the amount of resource consumed in a transaction and the general total amount of resource available pertaining to governor limit. © METHOD VERSIONS — ach Limit method has to versions. One versions fr determining the , amount of resource that has already been consumed or sed upina current transaction. The ather version contains the term “limit” and returns the total amount of resource that can be used, \ ay a (6 rocusovroRce a Limits Methods for Testing Governor Limits ® AVAILABLE RESOURCE . By using the two versions ofa certain Limite method, the remaining amount of resource that stil avaliable can be calculated, ® EXAMPLE METHOD faceless tos ete thebeats es poser genta rtanste tna ots Y | Totti sci oop om ett la (~m ‘rater (6 rocusovronce x| Test.startTest() and Test.stopTest() Example ‘Two sets of governor limits are monitored inthe unit test below - one is inside the boundaries of startTest and stopTest, and the other is outside. ‘Umits.getDmistatements|) method - A (one DML statement was called "soni Lingeostsensssonx4— [ing start Test and stopTest. : core TT 5] ra outside startest and stooTest. (@ rocusovronce | Testing Permission Set Groups (@ FoousoyroRce 4 Testing Permission Set Groups ‘When testing permission set groups, the calculatePermissionSetGroup() method can be used to recalculate the aggregate permissions in the permission set group. sticisrowmste| — (Whenevera permission set is added, edited. oF ‘are accurate, The tats ofa permission set group canbe “Updated! meaning ts combined permissions 1 tre option to wets ve grt passion | emer te added permistons the status Ie "Outdated" tcannot be sesigned toa user , (@ rocusoyrorce as| deleted ina permission set group. acaleulationis ‘applied toensure thatthe aggregate permissions Testing Code as Another User (@ rocusovronce «| h Different Users Salesforce allows executing code in the context of a specified user for testing by using the ‘System.runAs method. Testing Code ‘Apex code runs in system mode by default, which means permissions and record sharing ofthe carrent user arenot considered. USER CONTEXT ‘The System runemethod allow tet method tarun inthe context ofan exiting ser oF ane (@ rocusovronce | Testing Code with Different Users RECORD SHARING USER & FIELD-LEVEL PERMISSION, User permissions and e-evel permissions in the System run&smethod are not enforced, RUN AS METHOD AVAILABILITY ‘The SystemrunAs method can only beusedin test methods. (@ rocusoyronce x| Testing Code h Different Users SYSTEM CONTEXT Ea USER LICENSE, User license limits are ignored, so any number of users can be crested programmaticaly, DMLLIMIT ‘Acalltorunds counts against the total number of DML statements NESTED METHODS ‘The runs methods can be nested, or another runs method can be contained ina eanAs method (@ rocusovronce Testing Code with Different Users MIXED DML ‘Mixed DML operations canbe performed by enclosing them within the runs block SETUP OBJECTS Setup objects can be inserted or updated together with other sObjects using the uns block (@ roousovronce Test as Different Users System.runAs enables code to run in the context ofa specified user to test code behavior and record access to the user Feae atte od testa ite p= [nich otro often = tnd Oe neil [execute code as newUser (@ rocusoyroRce Testing Flows & Processes Writing a Unit Test for Flows Some implications of writing a test class for a flow: RETRIEVE THE OUTPUT VERIFY THE OUTPUT Output variables can be retrieved trom alow The flow outputisused to determine byusing the getVariableValuel) method of the Flowinterview object. whether or not the flowis working as expected START THE FLOW The autolaunched flow can be run by cling the start) method ofthe Flov interview object. INCREASE COVERAGE Invoking the low ina test class increases the flow tet coverage. USE A MAP. Avariable of Map datatypeisusedtoset Input parameters fer a flow. (@ roousovtoRce | Sample Flow Configuration Below is @ sample configuration of an autolaunched flow that accepts a Project record and creates @ Project Log tecord for the given project. ‘Set field values for eS the new record me ‘Assign the generated record = Ito an output variable = (@ rocusoyroRce 4“ Example Unit Test for a Flow ‘The following shows an example unit test to testa flow that automatically creates a log record when a project record is created. gene (create test data fot = wn rafect_stamenvot oof stanns_ovvetfy, "ering nt rm «mami ints _ pean) , (@ rocusovrorce 4 Testing Flows with External Services ‘Apex unit tests can also be created for flows that use an invocable action with External Services. The HttpCalloutMock interface can be used to simulate the callout tothe external service endpoint. speton-acertegual' ast, aut etwatr( accent) - reapmesetaateic (@ roousoytonce Testing Flows with External Services ‘The flow test class sets up the HTTP callout mock for the external service action, creates and runs the flow interview, and then asserts the actual flow output parameters with the expected test values. eaten ROIC ace samcanortaertertaat ote wld teststogmtortatercetion) ( —_ ‘stsevonatipnintek enya tects Os ecrigy sce treat =n apps fc PERAIGGAtSptdoiarteton © leer reine senate Sern aeeatnis 5 sl (Stig) stature gtartabeabe Fla") fen aucegute nes (aegjsateararnitian perenne cttstnarce Dy (@ FocusonroRce a] Writing a Unit Test for Processes “There are some implications when writing test class for a process: INVOKE PROCESS ..f \irting theses involves rating an Apetest metho thst invoke the process. © VERIFY RESULTS “The results produced by the invoked process is validated to ensure that ‘the process is working as expected, @ INCREASE COVERAGE Invoking the processin a test clas increases the flow test coverage. (@ rocusovrorce Example Unit Test for a Process Below tests a process which automatically updates a field value on the Project record to Assigned when ‘a project manager, which is @ lookup field, is assigned to the project. atest 04 tnt Poss stat_cndn' rect. acenge_e = pope je = ET an en t_ MOE e Seemseil eC Asan (@ rocusovronce Calculating the Flow Test Coverage The minimum test coverage percentage required for flows and processes is independent from the. Apex code coverage requirement. To calculate the flow test coverage, the following are performed: © DETERMINE ACTIVE FLOWS/PROCESSES re a Teeter eee orga the Tooling APD. QRUNALLTESTS Ruma testsinthe or (6 rocusovrorce Calculating the Flow Test Coverage (© DETERMINE COVERED FLOWS/PROCESSES Determine the numberof activ auttaunched flows and processes that have est coverage athe Tooling API CALCULATE TEST COVERAGE Divide the number of ative autolaunched flows that have test coverage by the total number of active autolaunched flaws and procestes. (@ rocusovrorce Example of Calculating the Flow Test Coverage For example, a total of 20 active autolaunched flows and processes were found when running the query: “Then after running all tests inthe org, it vas determined that the total number of active autolaunched flows and processes that have test coverage was 12 by running the query below: Meaning. there were Bother active lows oF processes that were not invoked in any ofthe est classes, (acomplia /20- 0 (@ rocusovronce DEPLOYED AS INACTIVE Active processes and flows ae deployed 2s, inactivein production orgy defauit (@ rocusovronce Test Data Sources (@ rocusoyroRce Testing Flows and Processes ‘Some implications of deploying process and flows: TO DEPLOY AS ACTIVE Todeploy processes and ows as active, the Deploy processes and flows ‘ctve option must be enabledin Process Automaton Setting FLOW TEST SCREEN FLOWS COVERAGE EXCLUDED Thetestingcoverage || Theflowtest coverage percentage requirement for flava is independent from the Apexcode coverage requirement and| isset manually in Setup requirement applies to processes nd flows, butit does not apply toflows that have screens. Salesforce allows several options for providing test data to test classes. Test Data Sources Overview Create common test data for eee eee every test method inthe lass Create Test Data Factory public @ ‘oO tity class with reusable clas, Pre-Existing Data Access Acces preeristingdatausing istestSeealbatactru @ Price Book Entries motion Retrieve standard price Book ID tocreate prcebook entries. Create test datacirectyin the test method Usestatic resources with Test loadData methos to populate test records. (@ rocusovronce Creating Test Data Programmatically When test data is created through a test method of atest data factory class, the following should bbe considered, © DATAIS TEMPORARY Test data created programmatically s temporary and does not persist in ‘the databave © DATAISROLLED BACK ‘Test records are rolled back when the unit test finishes execution. @ NONEED TO DELETE DATA {At the conclusion of test, test data doesnot need tobe deleted (@ rocusovronce Creating Test Data Programmatically NODATACOMMITTED Salestorce records createdin test methods are not committed to the databace. 4 NO DATA PERSISTENCE Updates and deletions to existing records dont persist after test (@ rocusoyroRce Dleing AtnctCatuin (@ rocusovronce VINNIE WLTSLOCLUup for Test Data Test setup methods are used to programmatically ereate test records Test Setup Methods ‘accessed in every test method inthe test class. © CREATE TEST DATA The test setup method, or the method annotated with @testSetup is used tocreate test data, which become availabe to test methods inthe test, ¢ REUSETEST DATA a ‘Common test data can be created which avoids the need tore-create the ‘Test setup methods executed frst before any test method in the test ene Naya! = © SETUPISRUNFIRST La classy the testing framework (@ rocusovronce nce, and then the records can be Test Setup Methods © TEST DATAIS RESET ‘Any changes to the record created in the @testSetup method willbe rolled back after each test method finishes execution, © TEST DATA ACCESS Records thatare created na test setup method become available tall test methods inthe test class. © TEST DATA ROLLBACK (iv It atest method makes changes to the records, such as record field updates or record deletions, those changes are rolled back after each test method finishes execution (@ rocusoyroRce Test Setup Methods © ORIGINAL STATE “The original unmodified state ofthe records are aways accessed bythe next executing test method © METHOD SYNTAX Test setup methods have no arguments and no return value. @ TEST SETUP SUPPORT ‘Test setup methods will not be supported the test class or test method hhas acess to existing datainthe og using the GisTest(SeeAllData-true) ‘annotation, (@ rocusoyroRce Test Setup Methods METHOD LIMIT Thereisalimito one test setup methed only per test lass. et ~ kp © TEST SETUP ERROR ‘Anerror encountered inthe test setup method will cause the entire test to fal, ands a result, no test methods willbe executed at al (@ rocusovronce Test Setup Methods An example unittest that tests an Apex trigger functionality a ene ene {create est data] eae & Retrieve the testdata Spoil oes optremiaa a, Set Cod tn, Cosette, eect amt ‘Checkifrewultsare vad (@ rocusoyroRce Using Test Utility Class (@ rocusoyroRce a Test Utility Classes Common test utliy classes are public test classes that contain reusable code for test data creation, @ TEMPORARY DATA Test data created programmatically is temporary and doesnot persistin thedatabase, Public test utility lasses ae annotated with @isTest to exclude Ifrom the ‘ora’scodesizelimit and executein test context. © CLASS AVAILABILITY ‘They can only be called by test methods and net by non-test code. (@ rocusovronce «| Test Utility Classes ® AVOID DUPLICATION Duplicationof test datacreationor helper methods are being avoided and make the code easier to maintain, ret) 9} ® Dataserur The methodsin a pubic utility lass can be called by any test method in : ‘Apexclasses to setup test data before running the test nd ACCESS MODIFIER “The methodsin public utility cass shouldbe declared as public or _lobal tobe visible totest classes. (@ rocusoyroRce «| Creating Test Data Using Utility Method Below is a sample test class thet uses the test uty class to create records used forthe test. Sree fee | 5] ieee state wd tetccmipateg Sree cae ee (6 rocusovroRce a Test Data Factory Example Below is a sarnpe test uty class with a method that creates and returns test accounts. estanaractary ( sc Usted crore ine cit ( scomeaiegs ) (@ rocusovronce Using Static Resources as Test Data (@ rocusovronce Create Data from Static Resources Static resources and Test.loadData method can be used to populate data in test methods without ‘writing several ines of code. © TEST DATAFILE Test data shouldbe prepared and saved ina CSV flees © STATIC RESOURCE FILE The CSV file shouldbe uploaded inthe orgas astaticresource. @ METHOD PARAMETERS “The TestloadData method requires the Object type token andthe name ofthestatic resource. (@ rocusoyroRce Create Data from Static Resources © 1eS1 DAIAFILE FUKMAL AMIME type of textcsvis assigned to the stati resource once itis uploaded, ands used to determine the default action when the resource Isfetched METHOD EXECUTION ‘The Test loadData i calledinside the test method thatrequireit. @ RETURN VALUE “The TestloadData method returns lst of sObjects foreach record inserted. METHOD PREREQUISITE Astaticresource shouldbe created before callingthe TestoadData ect 0 sossonet : CSV File Uploaded as Static Resource Below shows the details of» CSV fle that i uploaded in State Resources. Sy : ‘ Rept Seine — aH Tanioe — eetewsiatiernson 256Te os (@ rocuso\ronce a Loading Related Data When using static resources for loading test data, it is possible to relate records by using fake Ids on ‘the record Id and lookup field Id re now : ‘fewer Monfeworscon ne ; Axor htniinensm Sere : damon” twmaeeon 3870 IED feo) a ; a ; a (@ Focusonrorce a) Using a Static Resource for Test Data Below shows a sample test method that loads test data froma static resource. (@ rocusovronce u Pricebook Test Data =a (@ Focusovronce 15| Creating Pricebook Entries Creating price book entries with a standard price requires the ID ofthe standard pr ‘STANDARD PRICE BOOK ID ‘The getStandaraPricebookld method returns regardless of whether or nt the testcan query orgdata ‘TEST PRICE BOOK ENTRIES ‘The getStandorPricebookld method isused to {get the standard price book ID sothat price book entries can be created in tests, (@ rocusoiroRce 26 Getting Standard Pricebook Id This example shows how the getStandardPricebookld() method is used to create price book entr testdata 5 for (@ rocusoyroRce Using Existing Data as Test Data FocusonroRoe Access of Existing Data NOTES (© Saeteg dats be scesed Hs 500 quer ttc recomended a thats al bor depend © Hence itisrecommended to store datainstatc resources or rete date programmatically (@ roousoiroRce Access to Pre-Existing Data There are pre-existing org data that are always accessible to test classes. NO ACCESS BY DEFAULT Test classes donot have access by default topre-ensting data with some exceptions, ) ‘ACCESS TO ORG DATA Objects that are used to manage the org.or metadata abject, suchas Users, Profile, Organization and RecorType can be accessed inunit tests (@ rocusovrorce Example of Accessing Pre-Existing Data “The test method below lustrates access to exiting record types, users, and profiles. . EE (@ rocusovrorce SeeAllData Pre-existing data can be accessed by annotating the test class or method with GisTest(SeeAliData=true). CLASS ANNOTATION COVERAGE ‘The isTestSeealDeta-true anntation applies to ll test methodsin ates class. CLASS VS METHOD ANNOTATION, Ita test methods annotated with sTestSeelDta=fase) andthe containing class is annotated with [sTestSeeADatastrue).orgdata access isnot restricted for that method (@ rocusovrorce Example of SeeAllData ‘Test class below illustrates the different results of two annotated test methods, 5 Se eee Tiree Et Daa estes UsR.OEG IDEN nopasie0 eR De —_[}OEDUGENe = 125 Executing Tests (@ rocusovroRce # Executing Unit Tests The following tools can be used to run unit tests in Salesforce: © Apex Test Execution © Apex lasses page (Run All Tests) =a 1@ Developer Console 1@ Visual Studio Code © API(SOAP API, Tooling REST API, etc) (@ rocusovronce ss| Grouping Unit Tests Salesforce allows the following groupings of unit ests to be run: SINGLE CLASS TEST SUITE a Some o all methodsin aspecine class A predefined suite of classes can berun MULTIPLE CLASSES: fanfam] ALL TESTS Fas) #2 inanorgcanbe run Some or all methodsin asetof clases (@ rocusoyroRce «| Test Options for Change Sets Four types of test options are available when validating or deploying a change set. Each Apex ‘component Alltests inthe org Alltestsinthe org Irvokedinthe wennoen enunncane sSecncinedin | | escermaadin | || gg@eliedest Itaalezmaragst || inialovmaregad |) Sasesmusthave lage a (@ rocusovrorce Running Specified Tests Selected tests, specified tests, is a testing option, which allows specifying the test classes to execute, In this mode, the requirement is as follows: DEPLOYMENT REQUIREMENT Ifthe code coverage of any Apex components less than 75%, the e validation wil fall and deployment isnot allowed toproceed. @ RUNNING SPECIFIED TESTS in Running subset of tests results to quicker test runs. Specified tests can Tay also beruninthe Metadata API and are exposed totooks that are based ea ‘on Metadata API, suchas the Ant Migration Too. (@ FocusonroRcE | Running Specified Tests e INDIVIDUAL CODE COVERAGE Code coverages computed individually for ech Apexclass and tiger e andi diferent from the ovral cde coverage percentage. ‘© SPECIFYING APEX CLASSES be ere ‘Only test classes can be specified, not individual test methods. When eae selecting Rn specie tests inthe Ul, for example, names of the test rn classes are specified in a comma-separated list. (@ Focusonrorce ey Unit Test Limitations The following features are not supported in unit tests. Unit tests cannot send outbound emails When a ni tes includes Apex code that sends an email message. it may run successfully, but no emails » actually sent out from the org s APEXCALLOUTS Unit tests cannot perform HTTP callots. In order to test Apex cod that perform calouts, mock responses ae created using the HttpCalloutMock interface Apex Test Execution Page (@ rocusovronce Apex Test Execution The following ist the lifferent options or modes available when running tests inthe Apex Test Execution page ALLOR INDIVIDUAL CLASSES Anoption to select either lor individual Apex test classes torunis allowed, © SKIP CODE COVERAGE Anoptionto skip computation of code coverage during the test execution ieavaliable, ‘@ PARALLEL TEST EXECUTION “The selected tests to runare placedin an Apex Job queue and runin parallel by default. parallel mode causes issues, an option to disable itis provided. (@ roousovronce Apex Test Execution ASYNCHRONOUS EXECUTION Tests that are executed nthe Apex Test Execution page are run aeynchronoush. : 4q a ‘ MYNAMESPACE TESTS Namespace option inthe drop-down list. ALLNAMESPACES The option (All Namespaces] will display al test classes regardless of the namespaces they belong to, (@ rocusovrorce Apex Test Execution © MANAGED PACKAGE TESTS Tests from installed managed packazes canbe fitered by electing the managed package's corresponding namespace provided nthe rop-downlist 4 CODE COVERAGE DETAILS ‘Alter testshave completed, code coverage details can be viewed by licking onthe Developer Console button. (@ rocusovronce Apex Test Execution © TEST EXECUTION LIMIT Nogreater than 500, or 10 multiplied bythe number of test classes, can bbeexecuted every 24 hours. For sandboxes and Developer edition orgs, ‘the limits 20 multipied by thernumber of test classes @ TEST EXECUTION HISTORY Alltest results can be viewed by clicking on the View Test History link button above the test results table, (@ roousovronce Apex Test Execution A list ofthe unit tests tat are executed are displayed in table which shows the status, clas, and Tesult ofthe test. Apex Test Execution (@ rocusovrorce Apex Test Execution ‘The Select Tests button opens the window for selecting which test classes to execute ‘Apex Test Execution Si] omecees or ert (@ rocusovrorce | Skip Code Coverage in Apex Test Execution ‘Skipping code coverage canbe enabled inthe Test Classes window. ‘Apox Test Execution retcme . = —— | (@ roousovronce Skipping Code Coverage Skipping of code coverage computation is allowed by enabling the setting before the test execution COVERAGE COMPUTATION SKIPPED. Code coverage wll be skipped for ll executed tests until the Developer Consoles closed, orwhen the Skip Code Coverage settings enabled SKIP CODE COVERAGE IN APEX TEST EXECUTION ‘The kip Code Coverage options avalablein the Apex Test Execution page via the Test Classes window for selecting tests torun (6 rocusoyroRce 5] Skipping Code Coverage ‘SKIP CODE COVERAGE IN DEVELOPER CONSOLE ‘The kip code coverage checkbox is available nthe Specify Run Parameters dialog box. which can be openea via the Settings button ater clicking onthe Test-» New Run menu option inthe Developer Console. SPEED UP TEST RESULTS ‘Skipping code coverage will speed up test execution and return theresuits of thetests faster Inthis ‘mode, no code coverage information willbe provided at all (@ rocusoyroRce 00 Execute Tests in Developer Console [esenconn Test Suite in Developer Console Developer Console can be used to execute al test methods in a test class or run all tests in an org. In ‘addition, unit tests can be grouped together ina test suite to execute specific test methods: Fromasingleclass ff From multiple (@ rocusoyroRce | Test Suite in Developer Console A test suite is a collection of Apex test classes that is grouped and run together. This enables to ‘conveniently run the same subset of tests whenever required. MANAGE TEST SUITES ‘TEST SUITE CLASSES ‘The Suite Manager isused to ‘TEST SUITE FOR Suite Managers used to manage DEPLOYMENT. create.edit,delete,orrename || which Apextest classes are ‘Atest suite can becreated which test utes contained na testsuite, isrunevery time to prepare for deploymentor Salesforce release updates. (@ rocusovrorce Creating a Test Suite in Developer Console ‘test suite can be created in by clicking on New Suite option under the Test menu (ore coms =o) (Pykomeres) = (@ rocusovronce Skip Code Coverage in Developer Console ‘Skipping code coverage can be enabled via the Specify Run Parameters window. See _ = ea Se eel (@ rocusovtonce Run All Tests in Developer Console ‘Torun all tests from the Developer Console, click on the Run All option from the Test menu = eran Fale es wl ect ortho mm Le Es iuternnetediinettee, | =e sch are ged nte Test [Cicktorunalltests]Zoocc ase (@ rocusoyroRce | Run All Tests in Apex Classes Page All tests can algo be run by clicking on the Run All Tests button available on the Apex Classes page in Setup. Apex Classes. semnn@ EE nn | ptiremnacmanen Cliekiowreutealltests (@ rocusoyronce | Execute Tests in Visual Studio Code (@ roousoiroRce Visual Studio Code Visual Studio Code can also be used to execute Apex tests SOFTWARE REQUIREMENTS: FY oss Vi stcioCad or tet Salesforce Cate Salesforce Etro Pack needs tobe installed, FXECIITIAN OPTIONS aso possible to execute al tests that ae avaiable (@ rocusoyroRce Executing Tests from the Apex Test Sidebar The Apex Test Sidebar automatically detects Apex tests and displays the test classes and methods inalist, e RUNASINGLE TEST METHOD, = . Hover onthe name ofa tst method andcliekonthe Run Single Test Oo | oe button. \a ¢ RUNALLTEST METHODSIN ACLASS g : Hove onthe fart dpa the Run Tota ation 4 é . 4 RUNALLTESTSIN ALL CLASSES Hover on top ofthe Apex Tests area and lick on the Run Tests button (@ rocusovronce Executing Tests from the Editor The following options are available when running tests from the editor SINGLE TEST METHOD, Click onthe Run Test ink displayed above the ethod definition, fas] ml] AULTEST METHODS IN ACLASS Faas] “ion an Tt spe above tbe ‘Apexclass definition, (@ roousovronce Running Tests in Visual Studio Code Running tests and viewing test results in Visual Studio Code Fest results are shown the Output panel (@ rocusoyroRce 1 Execute Tests Using an API (@ rocusoyroRce ti Test Execution Using the API Tests can be run synchronously of asynchronously using SOAP API calls and objects, ALL OR SELECTED TEST CLASSES Allor specific test lasses can be executed ing the API TOOLING API Tooling REST API can aso be used to.un tests. ‘ASYNCHRONOUS TESTING The ApexTestQueueltem objectcanbe used toadd tests oan Apexiob queve and run them asynchronously. ‘CHECKING RESULTS ‘The ApoxTestResult object can beused to check the result ofan Apex test method execution. SYNCHRONOUS TESTING Tests canbe runsynchronously by using the runTests) call provided by the SOAP API (@ roousovronce Execute Unit Tests Using the SOAP API The following shows sample code that runs tests asynchronously and returns a job identifier sect) anos» tet &d Fb uncle WORE ee EE “ee ‘F teloner steed >t > (@ rocusoyroRce ube static vod chackTestathod Id $0686) ( sgoctaseecule[] results = FROM avexTestREsUIC % tor (apenrartReratt 2 reste) { Systensebus(e-ApexClotssae + °.' + esathodane «°° + esoutcon); : > > (@ rocusovroRce Retrieve Test Results Using the SOAP API Below shows sample code for retrieving test results based on a job identifier. The Tooling REST API can be used to perform asynchronous or synchronous test. The following shows. (@ rocusoyronce Run Unit Tests Using the Tooling API ‘two ways of requesting an asynchronous test execution. =a “otest asynchronously, the ‘rntestsAsynchronous/ resource is Used To run test synchronously, Sere, “eet (@ rocusoyroRcE Managed Packages and Unlocked Packages Manaped Packages and Unlacked Packases 5] When running the SFDX report command to retrieve details of a package version for second-generation ‘managed or unlocked packages, the output ean also include code coverage detail, MANAGED PACKAGES 2nd-generation managed packages, or also known as managed 2GP, are . sed for distributing apps on AppExchange using Salesforce DX. “=m, . ei ‘@ UNLOCKED PACKAGES j \ Saeco tree . a together sing the package development model to bul ape that are Q See cee nriree ef © CODE COVERAGE Code coverage details included inthe report can be used t identity hich Apex classes inthe package fall to meet the required code coverage percentage, Unlocked Packages The force:package-version:report command is used to retrieve details of a package version, To include code coverage details, the ~-verbose flag can be added = [Package version a (Code coverage details of Apex lasses inthe package willbe csplayed at theend (@ rocusovronce xo Other Concepts & Best Practices (@ rocusovtoRce ma Accessing Private or Protected Members Outside a Test Class Private or protected members can be exposed to test classes by using an annotation. USING @TestVi “The @testVisible annotation allows private or protected members methods, variables inner classes) tobe visible toa testelass (@ rocusovrorce va Testing Private Methods ‘The @TestVisible annotation exposes a private method to test classes ‘ait dn ott resus Fiat le ptt) ( es tora Sate vo etree carte , (@ rocusoyronce ~ Apex Testing with SObject Error Methods ‘The sObject class contains error methods that can be used in Apex testing to track and obtain errors, without performing any DML operation. sObject.addError() sObject hasErrors() sObject.getErrors() “Thismethad canbe used to Thismethod can beused to Thismethod can be used to ‘dynamically adderrorstospecite || determineitanobjectinstance || retrievealistoferrorsfor fields. contains any errors. specific object instance Maas = aeons meres eg ise = Sci mes “este owt elt || Sptemensertomo ove sh Sagres (@ rocusovronce mm ‘SObject Error Methods Example The following shows an example of using ofthe error methods in testing Apex code. EXE D ptfandsomartogtete ca asl tsuoy statue tay ns” Sack AF Si88 URL Ss acceetle cack) =a ‘Sptemcenertgues(y trans. ai)5 7 ier the ere shld oly be 8 ear asa rr = era SHERI copa en a Raa Se Se eee lpristeal ite! Srenanene | Sma ewe (@ rocusovrorce Deployment Requirements Overview Tests should cover as many lines of code as possible. Note the following before deploying Apex code: SUCCESSFULLY COMPILED CODE ‘Apex classes and trggersmust be compiled successfully and not throw ‘any uncaught exceptions or mit exceptions COMPLIANT CODE COVERAGE ‘Overall code coverage in anorg must beat least 75% for successful deployment. CODE COVERAGE EXCLUSION “Test clases and test methods are exclude from code coverage ‘requirement. (@ rocusovronce ve Deployment Requirements Overview © OPTIMIZE UNIT TESTS ‘Tests methods shouldbe optimized for every possible scenario and use ‘cseofan application. © APEX TRIGGER COVERAGE Each Apex trigger mustat least have one (1) line of code covered inthe test. (@ rocusovtonce Best Practices When Writing Test Classes Unit tests should set up conditions fora testing scenarios, such as normal, unexpected, boundary, and bad input values. MULTIPLE TEST CASES NON-PERSISTENT DATA, a Unit tests should take into consideration SM Unit tests donot commit changes, so test data doesnt need tobe deleted nor changes undone ater wee. DEIR crcaretest para ( verrvresutrs =i bake Unit tests should create their own test data and not depend on existing data in the org (@ rocusoyroRce systemassert) methods should be used to verify whether the expected results aremet Best Practices When Writing Test Classes SINGLE & BULK TESTS Create urittests that test code onasingle record as wellas on multiple records, TEST SUITES Tests should be added toa testsuite when a new bugis found in the odeto simplify regression testing FOCUS TESTS Unit tests should test only one aspect of code} ata time tomakeit easier tounderstand the purpose. TEST-DRIVEN Test-driven development or creating uri tests before writing new code can help to Understand how code will bused, (6 rocusoyroRce (@ Focusovtonce Unit Test Examples Unit Test Example Unit tests are used to ensure that code performs the required logic and produces the expected result In addition, test classes are required in order for any Apex code to be deployed in a production org SCENARIO Aflow uses aninvocable action that creates commission records for aclosed won opportunity based on the opportunity team members and roles, SOLUTION ‘Atest clas can be create that inves the flaw and verifies expected output ariablesif necessary. Then, the commission records are queried and validated. (6 rocusovroRce ? (@ rocusovroRce Unit Test Example ‘SCENARIO ‘An Apex trigger is being used to close allreated open ‘opportunities an transfer ther ownership toaspecinicuser whenever the status ofan Accounts set toinactive SOLUTION Attest class can be created that generates the necessary test Ea ‘count and opportunities, update the account status and then validate the opportunities. 2 (@ rocusovrorce Unit Test Example @ SCENARIO ‘An Apex classi being used 35a controller for communicating, with a third party messaging platform thats being used internally for sending automated messages. souution ss) ‘Atest class can be created that requires the use ofa mock cass ‘to simulate responses from the messaging platform Its predefined responses willbe used validating results. ‘e (© FocusovroRce Unit Test Example SCENARIO ‘Acustom controllers being used ina Visualforce page for eee, es =) SOLUTION A test class canbe created that requires the use of a PageReerenceclassto instantiate the Visualforce page that uses. ‘the controller and invoke and validate its operations. Unit Test Example scevanio oO rrcustirecasmesiecndets Lightning web component for managing user feedback such as assigning them to product owners ae track activities. SOLUTION © Like any other Apexclass atest class canbe created to execute _andvalidst each method thats being invoked from the Lightning web component. (@ rocusovrorce xs Learn More @ restinesoes © inant Ea © Manas Ses Aes Test Clases it Tet Sites @ socuteas (@ rocusoyroRce we Learn More @ sonrruntest © sestsesouces enn : : 7 O oni Dextomenis © sunning Subset of Tessin Deployment - Metadata APL @ restinenest Practices © cade conane Bes rate @ ‘outowitecood unit txts (@ rocusovronce

You might also like