100% found this document useful (1 vote)
23 views27 pages

Apex Testing Best Practices Guide

This document discusses best practices for testing Apex code and provides an overview of Apex testing. It recommends writing test methods to achieve at least 75% code coverage and emphasizes the importance of test automation. It outlines how to write test methods using System assertions to validate results. Special testing functions like System.runAs, Test.startTest, and Test.stopTest are covered. Testing anti-patterns like not validating results or using fake test methods are also discussed. The document concludes with an overview of Salesforce's roadmap for improving Apex testing capabilities.
Copyright
© Attribution Non-Commercial (BY-NC)
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
100% found this document useful (1 vote)
23 views27 pages

Apex Testing Best Practices Guide

This document discusses best practices for testing Apex code and provides an overview of Apex testing. It recommends writing test methods to achieve at least 75% code coverage and emphasizes the importance of test automation. It outlines how to write test methods using System assertions to validate results. Special testing functions like System.runAs, Test.startTest, and Test.stopTest are covered. Testing anti-patterns like not validating results or using fake test methods are also discussed. The document concludes with an overview of Salesforce's roadmap for improving Apex testing capabilities.
Copyright
© Attribution Non-Commercial (BY-NC)
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 Code Testing and Coverage Best Practices

Ryan Spraetz Product Manager Anand B Narasimhan Principal Consultant

Got Twitter? @forcedotcom / #forcewebinar Facebook? [Link]/forcedotcom


Like us in the month of March and enter to win an iPod Touch

Safe Harbor
Safe harbor statement under the Private Securities Litigation Reform Act of 1995: This presentation may contain forward-looking statements that involve risks, uncertainties, and assumptions. If any such uncertainties materialize or if any of the assumptions proves incorrect, the results of [Link], inc. could differ materially from the results expressed or implied by the forward-looking statements we make. All statements other than statements of historical fact could be deemed forward-looking, including any projections of subscriber growth, earnings, revenues, or other financial items and any statements regarding strategies or plans of management for future operations, statements of belief, any statements concerning new, planned, or upgraded services or technology developments and customer contracts or use of our services. The risks and uncertainties referred to above include but are not limited to risks associated with developing and delivering new functionality for our service, our new business model, our past operating losses, possible fluctuations in our operating results and rate of growth, interruptions or delays in our Web hosting, breach of our security measures, the immature market in which we operate, our relatively limited operating history, our ability to expand, retain, and motivate our employees and manage our growth, new releases of our service and successful customer deployment, and utilization and selling to larger enterprise customers. Further information on potential factors that could affect the financial results of [Link], inc. is included in our annual report on Form 10-K filed on February 24, 2011 and in other filings with the Securities and Exchange Commission. These documents are available on the SEC Filings section of the Investor Information section of our Web site. Any unreleased services or features referenced in this or other press releases or public statements are not currently available and may not be delivered on time or at all. Customers who purchase our services should make the purchase decisions based upon features that are currently available. [Link], inc. assumes no obligation and does not intend to update these forward-looking statements.

P
Join the conversation on Twitter: #forcewebinar @forcedotcom

Agenda
Testing philosophy Introduction to Apex Testing Writing tests and test tools Testing best practices and patterns Testing anti-patterns Testing Roadmap

Join the conversation on Twitter: #forcewebinar @forcedotcom

Testing Philosophy
Testing is key to successful development Testing requirements
75% code coverage Strive for better

Automation, automation, automation


Test suites catch regressions Manual testing does not scale!

Apex Test Hammer


Your 8M tests are part of our release process

Join the conversation on Twitter: #forcewebinar @forcedotcom

How do I test my code?


Testmethods! How easy is that?
public class HelloDevs{ public static String getGreeting(){ return (Test Away!); } static testmethod void testGreeting(){ String gr = [Link](); [Link](Test Away!,gr); } } @isTest private class TestHelloDevs{ static testmethod void testGreeting(){ String gr = [Link](); [Link](Test Away!,gr); } }

Can only be called from test code @isTest classes do not count towards code size limits

Join the conversation on Twitter: #forcewebinar @forcedotcom

Anatomy of a TestMethod
Demo
public class AccountProcessor{ public static Account ProcessAccount(Account acc){ //Do work here, for example: [Link] = 10; return acc; } public static testmethod void testProcessAccount(){ //Create test data Account acc = new Account(name = testAccount); //Run the code you want to test [Link](); acc = ProcessAccount(acc); [Link](); //Assert results [Link]([Link], 10); } }

Additional Resources on Apex Test classes and Test Methods


How to Write Good Unit Tests Apex Developer Guide Join the conversation on Twitter: #forcewebinar @forcedotcom

Verifying my code
[Link](); [Link]();

If you are not using asserts in your test code, you are probably not writing effective tests!

Join the conversation on Twitter: #forcewebinar @forcedotcom

Special System functions for testing


[Link](User){ } Test how your code interacts with your organizations sharing model Does not mimic CRUD/FLS
public class TestAsUser{ public static testmethod void testAsUser(){ User u = [SELECT id FROM User LIMIT 1]; [Link](u){ //Code here will respect sharing model } } }

Join the conversation on Twitter: #forcewebinar @forcedotcom

Special System functions for testing


[Link]() and [Link]() Extra set of governor limits to test your processes

public class TestAsUser{ public static testmethod void testProcess(){ //Do data set up here insert new Account(name = test); //Do your testing here [Link](); ProcessAccounts(); [Link](); //Do your aserts here [Link]() } }

Join the conversation on Twitter: #forcewebinar @forcedotcom

New in Spring 11!


[Link]() ApexOne: Fewer limits! From over 70 individual limits to 16 Tests now get the same governor limits as regular executions

Coming in Summer 11 at the end of the presentation


Join the conversation on Twitter: #forcewebinar @forcedotcom

Apex Testing Cookbook Recipes


Testing Http Callouts Testing when you have a private security model Using [Link]

Join the conversation on Twitter: #forcewebinar @forcedotcom

Testing HTTP Callouts


Visualforce mash up to display financial transactions for an Account HTTP REST API to get transaction data from external source XML Based request/response

Join the conversation on Twitter: #forcewebinar @forcedotcom

Testing PRIVATE sharing model


Display total Opportunity Amount on an account
Displayed through an inline Visualforce page in Account detail

Rollup depends on Users profile


Hardware Product Managers should only include Hardware opportunities Software Product Managers should only include Software opportunities

Account Sharing Model is PRIVATE


Opportunity Access is PRIVATE

Apex Controller runs in without sharing mode

Join the conversation on Twitter: #forcewebinar @forcedotcom

Using [Link]
Custom Email functionality
Uses standard standard Email Templates Uses Apex Email to send the email

Email templates presented to the end user will vary based on users Profile
Profile specific Email Templates are stored in different folders

Join the conversation on Twitter: #forcewebinar @forcedotcom

Summary
Use Apex Object Oriented constructs to simulate Mock Object pattern
Apex Interfaces Apex Class Inheritance and overloading

Use Apex Manual Sharing to open up test data records when using Private security model Use [Link] to execute logic specific to test methods
Only use this as an exception (to workaround areas that are hard to test)

Join the conversation on Twitter: #forcewebinar @forcedotcom

Apex Testing Anti Patterns


@IsTest
public class TestCoverageAntiPatterns{

public static void testmethod testButDontTest(){} public static void testmethod testWithExistingData(){} public static void testmethod testFakeTestCoverage(){}

Join the conversation on Twitter: #forcewebinar @forcedotcom

public static void testmethod

testButDontTest()
Trigger to set the Close Date of the earliest Opportunity that is closing on the account whenever an Opportunity is updated / inserted.

Join the conversation on Twitter: #forcewebinar @forcedotcom

public static void testmethod

testButDontTest()

Accounts attributes are not validated after the Opportunity is successfully inserted

Trigger has 75% test coverage, and hence can be deployed to production

Join the conversation on Twitter: #forcewebinar @forcedotcom

public static void testmethod testWithExistingData()

Hard coded RecordType Id. Record Types created in Sandbox are not guaranteed to have the same Id in production.. This Test class could fail when attempting to deploy to a production instance.

Join the conversation on Twitter: #forcewebinar @forcedotcom

public static void testmethod

testingDoneRight()

Get the Record Type Id based on the Name of the Record Type

Assert the Account Attributes after the opportunity is inserted successfuly

Trigger has 100% test coverage, and does not depend on any data in the org
Join the conversation on Twitter: #forcewebinar @forcedotcom

public static void testmethod testFakeTestCoverage()

Join the conversation on Twitter: #forcewebinar @forcedotcom

public static void testmethod testFakeTestCoverage()

fakeXXX() methods do not perform any business logic.

Fake methods count towards your Orgs Apex limits (2MB)

Will be able to deploy to production without actually testing anything.

Join the conversation on Twitter: #forcewebinar @forcedotcom

Apex Testing Roadmap


Asynchronous Test Execution already in pilot Asynchronous Testing API Test data partitioning Ability to check org features

Join the conversation on Twitter: #forcewebinar @forcedotcom

Resources
Developer Resources
[Link]

Apex Testing Resources


How to Write Good Unit Tests Apex Developer Guide

Apex Code Discussion Boards Cookbook

Q&A
Get a chance to win an iPod Nano by completing the survey at [Link]

Common questions

Powered by AI

Effective Apex test methods should utilize assertions using System.assert() or System.assertEquals() to verify code behavior, encapsulating logic in separate methods or classes and not relying on existing org data. Tests should achieve a minimum of 75% code coverage and incorporate automation to ensure scalability and regression capture . Use of @isTest decorated classes and methods ensures the code does not count against the organization’s declared code size limits, and Test.startTest()/Test.stopTest() should be used for simulating real-world transaction limits with governor controls .

In a 'private' sharing model, testing must consider the visibility constraints imposed by the sharing settings. Using the 'without sharing' keywords in Apex can alter how records are accessed, sidestepping normal sharing model restrictions during code execution. Moreover, test data should mimic varied sharing settings, and the use of 'Apex Manual Sharing' allows the opening up of test data records specifically for tests. However, testing strategies must also ensure that code which runs under normal sharing restrictions behaves as intended in actual production environments .

Antipatterns in test coverage include writing test methods that do not validate behavior ('testButDontTest'), relying on existing data in tests ('testWithExistingData'), and fake methods that do not test business logic ('testFakeTestCoverage'). These lead to overconfident deployment due to deceptive coverage metrics, potential deployment failures due to mismatched data assumptions, and an inability to safeguard real functional integrity, overall compromising test reliability and code robustness .

The Test.runAs() function is used in Apex to simulate running tests with a specific user context, respecting the sharing model of that user's profile. This function helps validate how code behaves under different user permissions, ensuring compliance with organization-wide defaults and role-based access rights. It does not mimic CRUD or field-level security considerations, so while runAs is powerful for sharing models, developers must manually ensure CRUD/FLS testing .

Automation is stressed in Apex testing because manual testing cannot efficiently scale or handle regression coverage for complex or repeated processes, whereas automated tests can run large suites of tests quickly and repeatedly. Automated tests ensure consistency and are integral to continuous integration and deployment processes. In contrast, manual testing is time-consuming, error-prone, and impractical with increasing code complexity and volume .

A 'PRIVATE' sharing model restricts data access strictly to owner and those explicitly granted permission, complicating tests that require broad data visibility for functionality that must be validated. In testing, data must be manually shared, or alternative sharing mechanisms within tests used to simulate different roles or profiles' access rights. Complex scenarios where business logic depends on aggregate data increases test setup complexity and requires thoughtful data preparation strategies within test methods .

Apex Interfaces and Class Inheritance facilitate 'Mock Object' patterns by allowing the creation of abstract classes or interfaces that are implemented by test-specific classes. These test implementations can mimic the behavior of complex or external dependencies without requiring the actual functionality in tests, isolating units for better focus and direct testing of code logic under controlled conditions .

Hardcoded data leads to test fragility where tests can fail if there is any change in environment-specific data, such as record types in production versus sandbox environments. Instead, dynamic fetching of data, for instance retrieving record type IDs based on names rather than directly using hardcoded IDs, ensures portability and reliability of tests across different organizational setups .

Test.startTest() and Test.stopTest() delineate a new set of governor limits in a test context, allowing the explicit isolation of the portion of the test that involves executing the code being tested. This practice is important to accurately simulate real-world behavior under Salesforce’s execution limits, ensuring that actual logic is evaluated independently of test setup operations, preserving resource quotas for core functionality .

Ensuring test coverage beyond the 75% requirement is crucial because it aids in exploring edge cases, reduces technical debt, and enhances code reliability across minor updates. Although 75% is the minimum standard, it does not guarantee full logical validation or safeguard against all potential errors. Higher coverage reflects thorough assessment of code paths and is often indicative of rigorous attention to software quality, catering to long-term maintenance and robustness .

You might also like