SlideShare a Scribd company logo
1 of 25
Download to read offline
Apex Unit Testing in the Real World

Dan Appleman, Full Circle CRM, CTO
Author: “Advanced Apex Programming for Salesforce.com and Force.com”
@danappleman
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 salesforce.com, 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
 product or service availability, 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, new products and services, 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 outcome of intellectual property and other litigation, risks associated
 with possible mergers and acquisitions, 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, our limited history reselling
 non-salesforce.com products, and utilization and selling to larger enterprise customers. Further information on potential factors that could affect the
 financial results of salesforce.com, inc. is included in our annual report on Form 10-Q for the most recent fiscal quarter ended July 31, 2012. This
 documents and others containing important disclosures 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 presentations, 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. Salesforce.com, inc. assumes no obligation and does not intend to update these forward-looking statements.
Recommended Testing Best Practices
Single action
Test to verify that a single record produces the correct, expected result.
Bulk actions
Any Apex code, whether a trigger, a class or an extension, may be invoked for 1 to 200 records. You must test not only
the single record case, but the bulk cases as well.
Positive behavior
Test to verify that the expected behavior occurs through every expected permutation, that is, that the user filled out
everything correctly and did not go past the limits.
Negative behavior
There are likely limits to your applications, such as not being able to add a future date, not being able to specify a
negative amount, and so on. You must test for the negative case and verify that the error messages are correctly
produced as well as for the positive, within the limits cases.
Restricted user
Test whether a user with restricted access to the sObjects used in your code sees the expected behavior. That is,
whether they can run the code or receive error messages.
Why don’t we do it?

 Consultants?
 In-house Developers?
 Package Developers?
Let’s Play a Game
20,000 Fictional Apex Developers were asked – why write
unit tests?
20,000 Fictional Apex Developers were asked – why write
unit tests?
20,000 Fictional Apex Developers were asked – why write
unit tests?
20,000 Fictional Apex Developers were asked – why write
unit tests?
20,000 Fictional Apex Developers were asked – why write
unit tests?
20,000 Fictional Apex Developers were asked – why write
unit tests?
20,000 Fictional Apex Developers were asked – why write
unit tests?
Testing to Requirements

1. Forces you to actually define requirements
2. Validates that what you built meets requirements
3. “Free” regression testing
4. “Free” target compatibility
5. May even get you code coverage.
All Testing is Bulk Testing - I
Bad code
public static testmethod void test1bad()
{
    Lead ld = new Lead(LastName='Testname',
                        Company='Testcompany');
    Test.StartTest();
    insert ld;
    Test.StopTest();
    Lead leadres = [Select ID from Lead where
                     ID = :ld.id];
           // Do some assert here
}
All Testing is Bulk Testing - II
Better code
public static testmethod void test1better()
{
    List<Lead> lds = new List<Lead>{
                      new Lead(LastName='Testname',
                           Company='Testcompany')};
    Test.StartTest();
    insert lds;
    Test.StopTest();
    Map<ID, Lead> leadsmap = new Map<ID, Lead>(lds);
    List<Lead> leadres = [Select ID from Lead where
                           ID in :leadsmap.keyset()];
          // Do some asserts here
}
All Testing is Bulk Testing - III
Centralize object initialization
public static List<Lead> InitTestLeads(
                                   Integer count)
{
    List<Lead> lds = new List<Lead>();
    for(Integer x = 0; x< count; x++)
    {
        lds.add(new Lead(LastName='Testname' +
          String.ValueOf(x), Company='Testcompany' +
          String.ValueOf(x)));
    }
    return lds;
}
All Testing is Bulk Testing - IV
Pull test code into a separate method
public static void test2support(Integer batchsize)
{
    List<Lead> lds = InitTestLeads(batchsize);
    Test.StartTest();
    insert lds;
    Test.StopTest();
    Map<ID, Lead> leadsmap = new Map<ID, Lead>(lds);
    List<Lead> leadres = [Select ID from Lead where
                                ID in :leadsmap.keyset()];
    // Do some asserts here
}
All Testing is Bulk Testing – Oh yeah!
And let the magic happen
@istest(oninstall=true)
public static void test2single()
{
    Test2Support(1);
}


@istest(oninstall=false)
public static void test2bulk()
{
    Test2Support(200);
}
Results:

 Direct functional/requirements validation
 Free regression testing
 Free target compatibility
 Cheap bulk testing
 Lower maintenance costs
 Most code coverage met
Bonus for Package Developers

 You can block tests using oninstall=false, but still need 75%
 code coverage to install.
 How do you shut down individual tests?
 How do you initialize object fields to address validation rules on
 a target system?
 How do you customize behavior during install while maintaining
 a single code base?
Static Resources to the Rescue
                                 Field initialization info
       Centralized object                                       Static Resource
      Initialization function

                                Control test
                                 execution
       Allow test to run?

         Test function
                                        Control behavior

                                             Other code
                                         (test or functional)
resources = [Select Body from StaticResource where Name = ‘predeployedresource' ];
Conclusion

 You can’t (and shouldn’t) ignore the economics of testing.
 Making general testing goals a priority over code coverage is the
 sound economic choice.
Next Steps

Question for chatter – tell us about a testing
challenge you overcame.


Stop by and chat at the Full Circle CRM booth
                                 btw… we’re hiring




                                                     www.AdvancedApex.com
No question? – Tell us about your favorite testing technique.
AdvancedApex.com

More Related Content

What's hot

Inverting The Testing Pyramid
Inverting The Testing PyramidInverting The Testing Pyramid
Inverting The Testing Pyramid
Naresh Jain
 
Testing using load runner performance testing
Testing using load runner  performance testingTesting using load runner  performance testing
Testing using load runner performance testing
SivaprasanthRentala1975
 
Test Requirements
Test RequirementsTest Requirements
Test Requirements
telab
 
The service minded tester
The service minded testerThe service minded tester
The service minded tester
Johan Hoberg
 
'An Evolution Into Specification By Example' by Adam Knight
'An Evolution Into Specification By Example' by Adam Knight'An Evolution Into Specification By Example' by Adam Knight
'An Evolution Into Specification By Example' by Adam Knight
TEST Huddle
 

What's hot (20)

Inverting The Testing Pyramid
Inverting The Testing PyramidInverting The Testing Pyramid
Inverting The Testing Pyramid
 
Apex Testing Best Practices
Apex Testing Best PracticesApex Testing Best Practices
Apex Testing Best Practices
 
The Automation Firehose: Be Strategic and Tactical by Thomas Haver
The Automation Firehose: Be Strategic and Tactical by Thomas HaverThe Automation Firehose: Be Strategic and Tactical by Thomas Haver
The Automation Firehose: Be Strategic and Tactical by Thomas Haver
 
'BIG Testing' with Hans Buwalda
'BIG Testing' with Hans Buwalda 'BIG Testing' with Hans Buwalda
'BIG Testing' with Hans Buwalda
 
Efficient And Effective Test Design
Efficient And Effective Test DesignEfficient And Effective Test Design
Efficient And Effective Test Design
 
Testing using load runner performance testing
Testing using load runner  performance testingTesting using load runner  performance testing
Testing using load runner performance testing
 
TDD, BDD and mocks
TDD, BDD and mocksTDD, BDD and mocks
TDD, BDD and mocks
 
Going Scriptless: Implementing Model-Based Test Automation in a Large Enterpr...
Going Scriptless: Implementing Model-Based Test Automation in a Large Enterpr...Going Scriptless: Implementing Model-Based Test Automation in a Large Enterpr...
Going Scriptless: Implementing Model-Based Test Automation in a Large Enterpr...
 
Test Requirements
Test RequirementsTest Requirements
Test Requirements
 
Oak testing profile2013
Oak testing profile2013Oak testing profile2013
Oak testing profile2013
 
Acceptance Test-Driven Development: Mastering Agile Testing
Acceptance Test-Driven Development: Mastering Agile TestingAcceptance Test-Driven Development: Mastering Agile Testing
Acceptance Test-Driven Development: Mastering Agile Testing
 
ATDD in practice
ATDD in practiceATDD in practice
ATDD in practice
 
Sap Integration Testing Test Scripting V0.1
Sap Integration Testing   Test Scripting V0.1Sap Integration Testing   Test Scripting V0.1
Sap Integration Testing Test Scripting V0.1
 
Testing in TFS
Testing in TFSTesting in TFS
Testing in TFS
 
Tdd & clean code
Tdd & clean codeTdd & clean code
Tdd & clean code
 
The service minded tester
The service minded testerThe service minded tester
The service minded tester
 
'An Evolution Into Specification By Example' by Adam Knight
'An Evolution Into Specification By Example' by Adam Knight'An Evolution Into Specification By Example' by Adam Knight
'An Evolution Into Specification By Example' by Adam Knight
 
Reliability And Validity Iv
Reliability And Validity IvReliability And Validity Iv
Reliability And Validity Iv
 
Database Testing Interview Questions By H2kInfosys
Database Testing Interview Questions By H2kInfosysDatabase Testing Interview Questions By H2kInfosys
Database Testing Interview Questions By H2kInfosys
 
Introducing Keyword-Driven Test Automation
Introducing Keyword-Driven Test AutomationIntroducing Keyword-Driven Test Automation
Introducing Keyword-Driven Test Automation
 

Viewers also liked

Marine collagen cz tiande
Marine collagen cz tiandeMarine collagen cz tiande
Marine collagen cz tiande
Liza Alypova
 
маски Dual system
маски Dual systemмаски Dual system
маски Dual system
Liza Alypova
 
Presentatie Masterclass eHerkenning (17 januari 2012) - eHerkenning voor geme...
Presentatie Masterclass eHerkenning (17 januari 2012) - eHerkenning voor geme...Presentatie Masterclass eHerkenning (17 januari 2012) - eHerkenning voor geme...
Presentatie Masterclass eHerkenning (17 januari 2012) - eHerkenning voor geme...
eHerkenning
 
Pmi pmbok-resume template-17
Pmi pmbok-resume template-17Pmi pmbok-resume template-17
Pmi pmbok-resume template-17
vishvasyadav45
 
strandstrongwhitepaper05-25-08
strandstrongwhitepaper05-25-08strandstrongwhitepaper05-25-08
strandstrongwhitepaper05-25-08
Greg Maurer
 
програм професионалне оријентације за родитеље
програм професионалне оријентације за родитељепрограм професионалне оријентације за родитеље
програм професионалне оријентације за родитеље
DTSSicevo
 
Katalog tianDe s novinky
Katalog tianDe s novinkyKatalog tianDe s novinky
Katalog tianDe s novinky
Liza Alypova
 
шампунь на основе мыльного ореха
шампунь на основе мыльного орехашампунь на основе мыльного ореха
шампунь на основе мыльного ореха
Liza Alypova
 
Deployment plan v1b cmmaao pmi pmp
Deployment plan v1b cmmaao pmi pmpDeployment plan v1b cmmaao pmi pmp
Deployment plan v1b cmmaao pmi pmp
vishvasyadav45
 

Viewers also liked (18)

Economy Matters May-June 2016
Economy Matters May-June 2016Economy Matters May-June 2016
Economy Matters May-June 2016
 
Cody Costa Rica Consulting - Twitter NextGen UX
Cody Costa Rica Consulting - Twitter NextGen UXCody Costa Rica Consulting - Twitter NextGen UX
Cody Costa Rica Consulting - Twitter NextGen UX
 
WAM-Pro Case Study Submission (Time & Labor System Upgrade)
WAM-Pro Case Study Submission (Time & Labor System Upgrade)WAM-Pro Case Study Submission (Time & Labor System Upgrade)
WAM-Pro Case Study Submission (Time & Labor System Upgrade)
 
Domestic Demand, Import Demand & Export Demand for Passenger Automobiles in I...
Domestic Demand, Import Demand & Export Demand for Passenger Automobiles in I...Domestic Demand, Import Demand & Export Demand for Passenger Automobiles in I...
Domestic Demand, Import Demand & Export Demand for Passenger Automobiles in I...
 
Marine collagen cz tiande
Marine collagen cz tiandeMarine collagen cz tiande
Marine collagen cz tiande
 
маски Dual system
маски Dual systemмаски Dual system
маски Dual system
 
Presentatie Masterclass eHerkenning (17 januari 2012) - eHerkenning voor geme...
Presentatie Masterclass eHerkenning (17 januari 2012) - eHerkenning voor geme...Presentatie Masterclass eHerkenning (17 januari 2012) - eHerkenning voor geme...
Presentatie Masterclass eHerkenning (17 januari 2012) - eHerkenning voor geme...
 
Общественный контроль за полицией в Волгодонске
Общественный контроль за полицией в ВолгодонскеОбщественный контроль за полицией в Волгодонске
Общественный контроль за полицией в Волгодонске
 
Important definitions
Important definitionsImportant definitions
Important definitions
 
Pmi pmbok-resume template-17
Pmi pmbok-resume template-17Pmi pmbok-resume template-17
Pmi pmbok-resume template-17
 
strandstrongwhitepaper05-25-08
strandstrongwhitepaper05-25-08strandstrongwhitepaper05-25-08
strandstrongwhitepaper05-25-08
 
програм професионалне оријентације за родитеље
програм професионалне оријентације за родитељепрограм професионалне оријентације за родитеље
програм професионалне оријентације за родитеље
 
Katalog tianDe s novinky
Katalog tianDe s novinkyKatalog tianDe s novinky
Katalog tianDe s novinky
 
шампунь на основе мыльного ореха
шампунь на основе мыльного орехашампунь на основе мыльного ореха
шампунь на основе мыльного ореха
 
teste1
teste1teste1
teste1
 
Cmmaao budget-pmi-pmp
Cmmaao budget-pmi-pmpCmmaao budget-pmi-pmp
Cmmaao budget-pmi-pmp
 
Deployment plan v1b cmmaao pmi pmp
Deployment plan v1b cmmaao pmi pmpDeployment plan v1b cmmaao pmi pmp
Deployment plan v1b cmmaao pmi pmp
 
Sendsteps Interactie Onderwijs
Sendsteps Interactie OnderwijsSendsteps Interactie Onderwijs
Sendsteps Interactie Onderwijs
 

Similar to Apex Unit Testing in the Real World

Elevate workshop programmatic_2014
Elevate workshop programmatic_2014Elevate workshop programmatic_2014
Elevate workshop programmatic_2014
David Scruggs
 
Testing Software Solutions
Testing Software SolutionsTesting Software Solutions
Testing Software Solutions
gavhays
 

Similar to Apex Unit Testing in the Real World (20)

10 Principles of Apex Testing
10 Principles of Apex Testing10 Principles of Apex Testing
10 Principles of Apex Testing
 
Software Testing Presentation
Software Testing PresentationSoftware Testing Presentation
Software Testing Presentation
 
Quit Jesting and Test your Lightning Web Components, Phillipe Ozil
Quit Jesting and Test your Lightning Web Components, Phillipe OzilQuit Jesting and Test your Lightning Web Components, Phillipe Ozil
Quit Jesting and Test your Lightning Web Components, Phillipe Ozil
 
Tests and Testability: Apex Structure and Strategy
Tests and Testability: Apex Structure and StrategyTests and Testability: Apex Structure and Strategy
Tests and Testability: Apex Structure and Strategy
 
Test Automation Best Practices (with SOA test approach)
Test Automation Best Practices (with SOA test approach)Test Automation Best Practices (with SOA test approach)
Test Automation Best Practices (with SOA test approach)
 
10 principles of apex testing
10 principles of apex testing10 principles of apex testing
10 principles of apex testing
 
Hands-On Workshop: Introduction to Coding for on Force.com for Admins and Non...
Hands-On Workshop: Introduction to Coding for on Force.com for Admins and Non...Hands-On Workshop: Introduction to Coding for on Force.com for Admins and Non...
Hands-On Workshop: Introduction to Coding for on Force.com for Admins and Non...
 
Bug Hunting with the Salesforce Developer Console
Bug Hunting with the Salesforce Developer ConsoleBug Hunting with the Salesforce Developer Console
Bug Hunting with the Salesforce Developer Console
 
Elevate workshop programmatic_2014
Elevate workshop programmatic_2014Elevate workshop programmatic_2014
Elevate workshop programmatic_2014
 
Introduction to Apex Triggers
Introduction to Apex TriggersIntroduction to Apex Triggers
Introduction to Apex Triggers
 
Dive Deep into Apex: Advanced Apex!
Dive Deep into Apex: Advanced Apex! Dive Deep into Apex: Advanced Apex!
Dive Deep into Apex: Advanced Apex!
 
Agile Network India | Be Customer Centric with Test First Development | Mamat...
Agile Network India | Be Customer Centric with Test First Development | Mamat...Agile Network India | Be Customer Centric with Test First Development | Mamat...
Agile Network India | Be Customer Centric with Test First Development | Mamat...
 
Testing Software Solutions
Testing Software SolutionsTesting Software Solutions
Testing Software Solutions
 
Advanced Apex Webinar
Advanced Apex WebinarAdvanced Apex Webinar
Advanced Apex Webinar
 
Performance Testing ISV Apps to Scale
Performance Testing ISV Apps to ScalePerformance Testing ISV Apps to Scale
Performance Testing ISV Apps to Scale
 
Performance Testing ISV Apps to Scale 11/9/2016
Performance Testing ISV Apps to Scale 11/9/2016Performance Testing ISV Apps to Scale 11/9/2016
Performance Testing ISV Apps to Scale 11/9/2016
 
Optimizing Your Agile Testing Processes
Optimizing Your Agile Testing ProcessesOptimizing Your Agile Testing Processes
Optimizing Your Agile Testing Processes
 
Finding Security Issues Fast!
Finding Security Issues Fast!Finding Security Issues Fast!
Finding Security Issues Fast!
 
Testing Interview Questions.pdf
Testing Interview Questions.pdfTesting Interview Questions.pdf
Testing Interview Questions.pdf
 
Qtp 92 Tutorial769
Qtp 92 Tutorial769Qtp 92 Tutorial769
Qtp 92 Tutorial769
 

More from Salesforce Developers

More from Salesforce Developers (20)

Sample Gallery: Reference Code and Best Practices for Salesforce Developers
Sample Gallery: Reference Code and Best Practices for Salesforce DevelopersSample Gallery: Reference Code and Best Practices for Salesforce Developers
Sample Gallery: Reference Code and Best Practices for Salesforce Developers
 
Maximizing Salesforce Lightning Experience and Lightning Component Performance
Maximizing Salesforce Lightning Experience and Lightning Component PerformanceMaximizing Salesforce Lightning Experience and Lightning Component Performance
Maximizing Salesforce Lightning Experience and Lightning Component Performance
 
Local development with Open Source Base Components
Local development with Open Source Base ComponentsLocal development with Open Source Base Components
Local development with Open Source Base Components
 
TrailheaDX India : Developer Highlights
TrailheaDX India : Developer HighlightsTrailheaDX India : Developer Highlights
TrailheaDX India : Developer Highlights
 
Why developers shouldn’t miss TrailheaDX India
Why developers shouldn’t miss TrailheaDX IndiaWhy developers shouldn’t miss TrailheaDX India
Why developers shouldn’t miss TrailheaDX India
 
CodeLive: Build Lightning Web Components faster with Local Development
CodeLive: Build Lightning Web Components faster with Local DevelopmentCodeLive: Build Lightning Web Components faster with Local Development
CodeLive: Build Lightning Web Components faster with Local Development
 
CodeLive: Converting Aura Components to Lightning Web Components
CodeLive: Converting Aura Components to Lightning Web ComponentsCodeLive: Converting Aura Components to Lightning Web Components
CodeLive: Converting Aura Components to Lightning Web Components
 
Enterprise-grade UI with open source Lightning Web Components
Enterprise-grade UI with open source Lightning Web ComponentsEnterprise-grade UI with open source Lightning Web Components
Enterprise-grade UI with open source Lightning Web Components
 
TrailheaDX and Summer '19: Developer Highlights
TrailheaDX and Summer '19: Developer HighlightsTrailheaDX and Summer '19: Developer Highlights
TrailheaDX and Summer '19: Developer Highlights
 
Live coding with LWC
Live coding with LWCLive coding with LWC
Live coding with LWC
 
Lightning web components - Episode 4 : Security and Testing
Lightning web components  - Episode 4 : Security and TestingLightning web components  - Episode 4 : Security and Testing
Lightning web components - Episode 4 : Security and Testing
 
LWC Episode 3- Component Communication and Aura Interoperability
LWC Episode 3- Component Communication and Aura InteroperabilityLWC Episode 3- Component Communication and Aura Interoperability
LWC Episode 3- Component Communication and Aura Interoperability
 
Lightning web components episode 2- work with salesforce data
Lightning web components   episode 2- work with salesforce dataLightning web components   episode 2- work with salesforce data
Lightning web components episode 2- work with salesforce data
 
Lightning web components - Episode 1 - An Introduction
Lightning web components - Episode 1 - An IntroductionLightning web components - Episode 1 - An Introduction
Lightning web components - Episode 1 - An Introduction
 
Migrating CPQ to Advanced Calculator and JSQCP
Migrating CPQ to Advanced Calculator and JSQCPMigrating CPQ to Advanced Calculator and JSQCP
Migrating CPQ to Advanced Calculator and JSQCP
 
Scale with Large Data Volumes and Big Objects in Salesforce
Scale with Large Data Volumes and Big Objects in SalesforceScale with Large Data Volumes and Big Objects in Salesforce
Scale with Large Data Volumes and Big Objects in Salesforce
 
Replicate Salesforce Data in Real Time with Change Data Capture
Replicate Salesforce Data in Real Time with Change Data CaptureReplicate Salesforce Data in Real Time with Change Data Capture
Replicate Salesforce Data in Real Time with Change Data Capture
 
Modern Development with Salesforce DX
Modern Development with Salesforce DXModern Development with Salesforce DX
Modern Development with Salesforce DX
 
Get Into Lightning Flow Development
Get Into Lightning Flow DevelopmentGet Into Lightning Flow Development
Get Into Lightning Flow Development
 
Integrate CMS Content Into Lightning Communities with CMS Connect
Integrate CMS Content Into Lightning Communities with CMS ConnectIntegrate CMS Content Into Lightning Communities with CMS Connect
Integrate CMS Content Into Lightning Communities with CMS Connect
 

Apex Unit Testing in the Real World

  • 1. Apex Unit Testing in the Real World Dan Appleman, Full Circle CRM, CTO Author: “Advanced Apex Programming for Salesforce.com and Force.com” @danappleman
  • 2. 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 salesforce.com, 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 product or service availability, 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, new products and services, 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 outcome of intellectual property and other litigation, risks associated with possible mergers and acquisitions, 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, our limited history reselling non-salesforce.com products, and utilization and selling to larger enterprise customers. Further information on potential factors that could affect the financial results of salesforce.com, inc. is included in our annual report on Form 10-Q for the most recent fiscal quarter ended July 31, 2012. This documents and others containing important disclosures 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 presentations, 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. Salesforce.com, inc. assumes no obligation and does not intend to update these forward-looking statements.
  • 3. Recommended Testing Best Practices Single action Test to verify that a single record produces the correct, expected result. Bulk actions Any Apex code, whether a trigger, a class or an extension, may be invoked for 1 to 200 records. You must test not only the single record case, but the bulk cases as well. Positive behavior Test to verify that the expected behavior occurs through every expected permutation, that is, that the user filled out everything correctly and did not go past the limits. Negative behavior There are likely limits to your applications, such as not being able to add a future date, not being able to specify a negative amount, and so on. You must test for the negative case and verify that the error messages are correctly produced as well as for the positive, within the limits cases. Restricted user Test whether a user with restricted access to the sObjects used in your code sees the expected behavior. That is, whether they can run the code or receive error messages.
  • 4. Why don’t we do it? Consultants? In-house Developers? Package Developers?
  • 6. 20,000 Fictional Apex Developers were asked – why write unit tests?
  • 7. 20,000 Fictional Apex Developers were asked – why write unit tests?
  • 8. 20,000 Fictional Apex Developers were asked – why write unit tests?
  • 9. 20,000 Fictional Apex Developers were asked – why write unit tests?
  • 10. 20,000 Fictional Apex Developers were asked – why write unit tests?
  • 11. 20,000 Fictional Apex Developers were asked – why write unit tests?
  • 12. 20,000 Fictional Apex Developers were asked – why write unit tests?
  • 13. Testing to Requirements 1. Forces you to actually define requirements 2. Validates that what you built meets requirements 3. “Free” regression testing 4. “Free” target compatibility 5. May even get you code coverage.
  • 14. All Testing is Bulk Testing - I Bad code public static testmethod void test1bad() { Lead ld = new Lead(LastName='Testname', Company='Testcompany'); Test.StartTest(); insert ld; Test.StopTest(); Lead leadres = [Select ID from Lead where ID = :ld.id]; // Do some assert here }
  • 15. All Testing is Bulk Testing - II Better code public static testmethod void test1better() { List<Lead> lds = new List<Lead>{ new Lead(LastName='Testname', Company='Testcompany')}; Test.StartTest(); insert lds; Test.StopTest(); Map<ID, Lead> leadsmap = new Map<ID, Lead>(lds); List<Lead> leadres = [Select ID from Lead where ID in :leadsmap.keyset()]; // Do some asserts here }
  • 16. All Testing is Bulk Testing - III Centralize object initialization public static List<Lead> InitTestLeads( Integer count) { List<Lead> lds = new List<Lead>(); for(Integer x = 0; x< count; x++) { lds.add(new Lead(LastName='Testname' + String.ValueOf(x), Company='Testcompany' + String.ValueOf(x))); } return lds; }
  • 17. All Testing is Bulk Testing - IV Pull test code into a separate method public static void test2support(Integer batchsize) { List<Lead> lds = InitTestLeads(batchsize); Test.StartTest(); insert lds; Test.StopTest(); Map<ID, Lead> leadsmap = new Map<ID, Lead>(lds); List<Lead> leadres = [Select ID from Lead where ID in :leadsmap.keyset()]; // Do some asserts here }
  • 18. All Testing is Bulk Testing – Oh yeah! And let the magic happen @istest(oninstall=true) public static void test2single() { Test2Support(1); } @istest(oninstall=false) public static void test2bulk() { Test2Support(200); }
  • 19. Results: Direct functional/requirements validation Free regression testing Free target compatibility Cheap bulk testing Lower maintenance costs Most code coverage met
  • 20. Bonus for Package Developers You can block tests using oninstall=false, but still need 75% code coverage to install. How do you shut down individual tests? How do you initialize object fields to address validation rules on a target system? How do you customize behavior during install while maintaining a single code base?
  • 21. Static Resources to the Rescue Field initialization info Centralized object Static Resource Initialization function Control test execution Allow test to run? Test function Control behavior Other code (test or functional) resources = [Select Body from StaticResource where Name = ‘predeployedresource' ];
  • 22. Conclusion You can’t (and shouldn’t) ignore the economics of testing. Making general testing goals a priority over code coverage is the sound economic choice.
  • 23. Next Steps Question for chatter – tell us about a testing challenge you overcame. Stop by and chat at the Full Circle CRM booth btw… we’re hiring www.AdvancedApex.com
  • 24. No question? – Tell us about your favorite testing technique.