SlideShare a Scribd company logo
1 of 15
Download to read offline
Unit Testing in Apex

Chamil Madusanka
Understanding Testing in Apex
• Testing is the key to successful long term
development
• critical component of the development process.
• salesforce.com strongly recommends to use a testdriven development process
• Test development that occurs at the same time as
code development.
Before deploy or upload the code or
package………..
•
•
•
•

75% of your Apex code must be covered by unit tests
All the tests must complete successfully
Every trigger has some test coverage (1%)
All classes and triggers must compile successfully
What to test?
• Single Action
– Test to verify that a single record produces the correct, expected
result.

• Bulk Action
– test not only the single record case, but the bulk cases as well

• Positive Behavior
– verify that the expected behavior occurs through every
expected permutation

• Negative Behavior
– Verify that the error messages are correctly produced

• Restricted User
– Test whether a user with restricted access to the sObjects used
in your code sees the expected behavior
Test Class
• Test classes defined by @isTest annotation
• Before Winter ’12 Release
– Test classes have to be private

• On Winter ‘12 Release
– Test Classes can be public or private
Test Class cont…….
• Public Test Classes
– Expose common methods for test data creation
– Setting up data that the tests need to run against.
– Methods of a public test class can only be called
from a running test
– Cannot be called by a non-test request
Test Class cont…….
• When you create a test method,
– Use static
– Use testMethod keyword
– Use void return type
– No any arguments
– No data changes performed in a test method
– Don’t send emails
– Cannot be used to test Web service callout
• The API for asynchronous test runs is a Beta release (Winter ‘12)
• For More : Force.com Apex code Developer’s Guide Page 153
Test Class cont…….
• The key methods to use in your unit tests are
the system.assert() methods
– System.assert(condition)
– System.assertEquals(x,y)
– System.assertNotEquals(x,y)

• For the security review, every test method
must have at least one system.assert()
method
Structure of Test class
@isTest
private classTest_class
{
public static testMethod void test_name()
{
//code_block;
}
}
Structure of public Test class for test data
creation
@isTest
public class TestUtil
{
public static void createTestAccounts()
{
// Create some test accounts
}
public static void createTestContacts()
{
// Create some test contacts
}
}
New IsTest(OnInstall=true) Annotation
• Control the Apex test classes during the package installation
• Can be used for managed or unmanaged packages
• No longer possible to bypass a failing test during package
installation
• A test method or a class won't be executed during installation
– Doesn't have this annotation
– Annotated with isTest(OnInstall=false)
– Annotated with isTest

• This annotation applies only to packages uploaded in Winter
’12 or later
IsTest(OnInstall=true) Annotation

cont…
public class OnInstallClass
{
public void method1()
{
// Some code
}
// This test method will be executed during the installation of the
// package.
@isTest(OnInstall=true)
static void test1()
{
// Some test code
}
// Tests excluded from running during the installation of a package.
@isTest
static void test2()
{
// Some test code
}
static testmethod void test3()
{
// Some test code
}
}
Best Practice for Writing Test Classes
• Write fully portable tests
–
–
–
–

You write tests in the context of a Developer or Sandbox org.
You can write tests that rely on specific pieces of data
If you do that, your tests will fail on deployment
Use relative URLs and query for names of data records rather than
their specific Ids.

• Don’t use production data in your tests
• Test expected behavior first, then unexpected behavior
– Start with testing simple cases, and test to make sure that what you
expect to happen is indeed happening.
– Then make sure to add test cases for behavior you don’t expect, but
could happen.
– This is why they tell developers never to write their own tests, because
we all believe our code will behave as expected.
Best Practice for Writing Test Classes cont…..
• If you find a bug, write a test to expose it before
you fix it
• Shoot for 100% coverage
– Try to test everything
– It’s not always fun or even possible, but try

• Don’t rely on Today()
– If you are using dates in your code, don’t build your
dates on Today()
– Use Date.newInstance(Integer year,Integer
month,Integer date)

– Use a date in the past
Reference
• http://www.salesforce.com/us/developer/docs/a
pexcode/salesforce_apex_language_reference.pd
f
• http://gokubi.com/archives/testing-bestpractices
• http://www.salesforce.com/us/developer/docs/a
pexcode/Content/apex_testing_example.htm
• http://www.salesforce.com/us/developer/docs/p
ages/Content/pages_controller_error_handling.h
tm

More Related Content

What's hot

Unit and integration Testing
Unit and integration TestingUnit and integration Testing
Unit and integration TestingDavid Berliner
 
Keyword Driven Testing
Keyword Driven TestingKeyword Driven Testing
Keyword Driven TestingMaveryx
 
Refactoring Legacy Web Forms for Test Automation
Refactoring Legacy Web Forms for Test AutomationRefactoring Legacy Web Forms for Test Automation
Refactoring Legacy Web Forms for Test AutomationStephen Fuqua
 
Tdd Ugialtnet Jan2010
Tdd Ugialtnet Jan2010Tdd Ugialtnet Jan2010
Tdd Ugialtnet Jan2010guestcff805
 
Unit Testing And Mocking
Unit Testing And MockingUnit Testing And Mocking
Unit Testing And MockingJoe Wilson
 
A Beginer's Guide to testing in Django
A Beginer's Guide to testing in DjangoA Beginer's Guide to testing in Django
A Beginer's Guide to testing in DjangoPsalms Kalu
 
Winning the battle against Automated testing
Winning the battle against Automated testingWinning the battle against Automated testing
Winning the battle against Automated testingElena Laskavaia
 
How and what to unit test
How and what to unit testHow and what to unit test
How and what to unit testEugenio Lentini
 
Unit testing, UI testing and Test Driven Development in Visual Studio 2012
Unit testing, UI testing and Test Driven Development in Visual Studio 2012Unit testing, UI testing and Test Driven Development in Visual Studio 2012
Unit testing, UI testing and Test Driven Development in Visual Studio 2012Jacinto Limjap
 
Unit testing
Unit testing Unit testing
Unit testing dubbu
 
Intro To Unit and integration Testing
Intro To Unit and integration TestingIntro To Unit and integration Testing
Intro To Unit and integration TestingPaul Churchward
 
Software testing tools
Software testing toolsSoftware testing tools
Software testing toolsGaurav Paliwal
 
NUnit Features Presentation
NUnit Features PresentationNUnit Features Presentation
NUnit Features PresentationShir Brass
 
Beginners - Get Started With Unit Testing in .NET
Beginners - Get Started With Unit Testing in .NETBeginners - Get Started With Unit Testing in .NET
Beginners - Get Started With Unit Testing in .NETBaskar K
 

What's hot (20)

Unit and integration Testing
Unit and integration TestingUnit and integration Testing
Unit and integration Testing
 
Keyword Driven Testing
Keyword Driven TestingKeyword Driven Testing
Keyword Driven Testing
 
Unit Testing (C#)
Unit Testing (C#)Unit Testing (C#)
Unit Testing (C#)
 
Refactoring Legacy Web Forms for Test Automation
Refactoring Legacy Web Forms for Test AutomationRefactoring Legacy Web Forms for Test Automation
Refactoring Legacy Web Forms for Test Automation
 
j meter
 j meter j meter
j meter
 
Tdd Ugialtnet Jan2010
Tdd Ugialtnet Jan2010Tdd Ugialtnet Jan2010
Tdd Ugialtnet Jan2010
 
Unit Testing And Mocking
Unit Testing And MockingUnit Testing And Mocking
Unit Testing And Mocking
 
Unit Testing
Unit TestingUnit Testing
Unit Testing
 
A Beginer's Guide to testing in Django
A Beginer's Guide to testing in DjangoA Beginer's Guide to testing in Django
A Beginer's Guide to testing in Django
 
Winning the battle against Automated testing
Winning the battle against Automated testingWinning the battle against Automated testing
Winning the battle against Automated testing
 
How and what to unit test
How and what to unit testHow and what to unit test
How and what to unit test
 
Unit Testing
Unit TestingUnit Testing
Unit Testing
 
Unit testing, UI testing and Test Driven Development in Visual Studio 2012
Unit testing, UI testing and Test Driven Development in Visual Studio 2012Unit testing, UI testing and Test Driven Development in Visual Studio 2012
Unit testing, UI testing and Test Driven Development in Visual Studio 2012
 
Unit testing
Unit testingUnit testing
Unit testing
 
Unit testing
Unit testing Unit testing
Unit testing
 
Intro To Unit and integration Testing
Intro To Unit and integration TestingIntro To Unit and integration Testing
Intro To Unit and integration Testing
 
Automated testing
Automated testingAutomated testing
Automated testing
 
Software testing tools
Software testing toolsSoftware testing tools
Software testing tools
 
NUnit Features Presentation
NUnit Features PresentationNUnit Features Presentation
NUnit Features Presentation
 
Beginners - Get Started With Unit Testing in .NET
Beginners - Get Started With Unit Testing in .NETBeginners - Get Started With Unit Testing in .NET
Beginners - Get Started With Unit Testing in .NET
 

Similar to Unit testing in Force.com platform

Episode 5 - Writing unit tests in Salesforce
Episode 5 - Writing unit tests in SalesforceEpisode 5 - Writing unit tests in Salesforce
Episode 5 - Writing unit tests in SalesforceJitendra Zaa
 
Principles and patterns for test driven development
Principles and patterns for test driven developmentPrinciples and patterns for test driven development
Principles and patterns for test driven developmentStephen Fuqua
 
Class9_SW_Testing_Strategies.pdf
Class9_SW_Testing_Strategies.pdfClass9_SW_Testing_Strategies.pdf
Class9_SW_Testing_Strategies.pdfFarjanaParvin5
 
Lecture (Software Testing).pptx
Lecture (Software Testing).pptxLecture (Software Testing).pptx
Lecture (Software Testing).pptxskknowledge
 
Unit Testng with PHP Unit - A Step by Step Training
Unit Testng with PHP Unit - A Step by Step TrainingUnit Testng with PHP Unit - A Step by Step Training
Unit Testng with PHP Unit - A Step by Step TrainingRam Awadh Prasad, PMP
 
An Introduction to Unit Test Using NUnit
An Introduction to Unit Test Using NUnitAn Introduction to Unit Test Using NUnit
An Introduction to Unit Test Using NUnitweili_at_slideshare
 
Software Testing
Software TestingSoftware Testing
Software TestingAdroitLogic
 
Test Driven Development with Sql Server
Test Driven Development with Sql ServerTest Driven Development with Sql Server
Test Driven Development with Sql ServerDavid P. Moore
 
Database Unit Testing Made Easy with VSTS
Database Unit Testing Made Easy with VSTSDatabase Unit Testing Made Easy with VSTS
Database Unit Testing Made Easy with VSTSSanil Mhatre
 
How to use selenium successfully
How to use selenium successfullyHow to use selenium successfully
How to use selenium successfullyTEST Huddle
 
Agile Software Testing the Agilogy Way
Agile Software Testing the Agilogy WayAgile Software Testing the Agilogy Way
Agile Software Testing the Agilogy WayJordi Pradel
 
Software Engineering Lec 10 -software testing--
Software Engineering Lec 10 -software testing--Software Engineering Lec 10 -software testing--
Software Engineering Lec 10 -software testing--Taymoor Nazmy
 
Test Driven Development Introduction
Test Driven Development IntroductionTest Driven Development Introduction
Test Driven Development IntroductionNguyen Hai
 
Test Driven Development
Test Driven DevelopmentTest Driven Development
Test Driven DevelopmentZendCon
 
Software testing part
Software testing partSoftware testing part
Software testing partPreeti Mishra
 
Automated testing overview
Automated testing overviewAutomated testing overview
Automated testing overviewAlex Pop
 
Test case management with MTM 2013
Test case management with MTM 2013Test case management with MTM 2013
Test case management with MTM 2013Raluca Suditu
 
03 test specification and execution
03   test specification and execution03   test specification and execution
03 test specification and executionClemens Reijnen
 

Similar to Unit testing in Force.com platform (20)

Episode 5 - Writing unit tests in Salesforce
Episode 5 - Writing unit tests in SalesforceEpisode 5 - Writing unit tests in Salesforce
Episode 5 - Writing unit tests in Salesforce
 
Principles and patterns for test driven development
Principles and patterns for test driven developmentPrinciples and patterns for test driven development
Principles and patterns for test driven development
 
Class9_SW_Testing_Strategies.pdf
Class9_SW_Testing_Strategies.pdfClass9_SW_Testing_Strategies.pdf
Class9_SW_Testing_Strategies.pdf
 
Lecture (Software Testing).pptx
Lecture (Software Testing).pptxLecture (Software Testing).pptx
Lecture (Software Testing).pptx
 
Unit Testng with PHP Unit - A Step by Step Training
Unit Testng with PHP Unit - A Step by Step TrainingUnit Testng with PHP Unit - A Step by Step Training
Unit Testng with PHP Unit - A Step by Step Training
 
An Introduction to Unit Test Using NUnit
An Introduction to Unit Test Using NUnitAn Introduction to Unit Test Using NUnit
An Introduction to Unit Test Using NUnit
 
Software Testing
Software TestingSoftware Testing
Software Testing
 
Test Driven Development with Sql Server
Test Driven Development with Sql ServerTest Driven Development with Sql Server
Test Driven Development with Sql Server
 
Test Driven Development
Test Driven DevelopmentTest Driven Development
Test Driven Development
 
Database Unit Testing Made Easy with VSTS
Database Unit Testing Made Easy with VSTSDatabase Unit Testing Made Easy with VSTS
Database Unit Testing Made Easy with VSTS
 
How to use selenium successfully
How to use selenium successfullyHow to use selenium successfully
How to use selenium successfully
 
Agile Software Testing the Agilogy Way
Agile Software Testing the Agilogy WayAgile Software Testing the Agilogy Way
Agile Software Testing the Agilogy Way
 
Software Engineering Lec 10 -software testing--
Software Engineering Lec 10 -software testing--Software Engineering Lec 10 -software testing--
Software Engineering Lec 10 -software testing--
 
Test Driven Development Introduction
Test Driven Development IntroductionTest Driven Development Introduction
Test Driven Development Introduction
 
Testing Angular
Testing AngularTesting Angular
Testing Angular
 
Test Driven Development
Test Driven DevelopmentTest Driven Development
Test Driven Development
 
Software testing part
Software testing partSoftware testing part
Software testing part
 
Automated testing overview
Automated testing overviewAutomated testing overview
Automated testing overview
 
Test case management with MTM 2013
Test case management with MTM 2013Test case management with MTM 2013
Test case management with MTM 2013
 
03 test specification and execution
03   test specification and execution03   test specification and execution
03 test specification and execution
 

Recently uploaded

AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsMemoori
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Commit University
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024Scott Keck-Warren
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brandgvaughan
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...Fwdays
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 3652toLead Limited
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyAlfredo García Lavilla
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek SchlawackFwdays
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Patryk Bandurski
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Mattias Andersson
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Mark Simos
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfAlex Barbosa Coqueiro
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 3652toLead Limited
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piececharlottematthew16
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Scott Keck-Warren
 

Recently uploaded (20)

AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial Buildings
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brand
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easy
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdf
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piece
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food Manufacturing
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024
 

Unit testing in Force.com platform

  • 1. Unit Testing in Apex Chamil Madusanka
  • 2. Understanding Testing in Apex • Testing is the key to successful long term development • critical component of the development process. • salesforce.com strongly recommends to use a testdriven development process • Test development that occurs at the same time as code development.
  • 3. Before deploy or upload the code or package……….. • • • • 75% of your Apex code must be covered by unit tests All the tests must complete successfully Every trigger has some test coverage (1%) All classes and triggers must compile successfully
  • 4. What to test? • Single Action – Test to verify that a single record produces the correct, expected result. • Bulk Action – test not only the single record case, but the bulk cases as well • Positive Behavior – verify that the expected behavior occurs through every expected permutation • Negative Behavior – Verify that the error messages are correctly produced • Restricted User – Test whether a user with restricted access to the sObjects used in your code sees the expected behavior
  • 5. Test Class • Test classes defined by @isTest annotation • Before Winter ’12 Release – Test classes have to be private • On Winter ‘12 Release – Test Classes can be public or private
  • 6. Test Class cont……. • Public Test Classes – Expose common methods for test data creation – Setting up data that the tests need to run against. – Methods of a public test class can only be called from a running test – Cannot be called by a non-test request
  • 7. Test Class cont……. • When you create a test method, – Use static – Use testMethod keyword – Use void return type – No any arguments – No data changes performed in a test method – Don’t send emails – Cannot be used to test Web service callout • The API for asynchronous test runs is a Beta release (Winter ‘12) • For More : Force.com Apex code Developer’s Guide Page 153
  • 8. Test Class cont……. • The key methods to use in your unit tests are the system.assert() methods – System.assert(condition) – System.assertEquals(x,y) – System.assertNotEquals(x,y) • For the security review, every test method must have at least one system.assert() method
  • 9. Structure of Test class @isTest private classTest_class { public static testMethod void test_name() { //code_block; } }
  • 10. Structure of public Test class for test data creation @isTest public class TestUtil { public static void createTestAccounts() { // Create some test accounts } public static void createTestContacts() { // Create some test contacts } }
  • 11. New IsTest(OnInstall=true) Annotation • Control the Apex test classes during the package installation • Can be used for managed or unmanaged packages • No longer possible to bypass a failing test during package installation • A test method or a class won't be executed during installation – Doesn't have this annotation – Annotated with isTest(OnInstall=false) – Annotated with isTest • This annotation applies only to packages uploaded in Winter ’12 or later
  • 12. IsTest(OnInstall=true) Annotation cont… public class OnInstallClass { public void method1() { // Some code } // This test method will be executed during the installation of the // package. @isTest(OnInstall=true) static void test1() { // Some test code } // Tests excluded from running during the installation of a package. @isTest static void test2() { // Some test code } static testmethod void test3() { // Some test code } }
  • 13. Best Practice for Writing Test Classes • Write fully portable tests – – – – You write tests in the context of a Developer or Sandbox org. You can write tests that rely on specific pieces of data If you do that, your tests will fail on deployment Use relative URLs and query for names of data records rather than their specific Ids. • Don’t use production data in your tests • Test expected behavior first, then unexpected behavior – Start with testing simple cases, and test to make sure that what you expect to happen is indeed happening. – Then make sure to add test cases for behavior you don’t expect, but could happen. – This is why they tell developers never to write their own tests, because we all believe our code will behave as expected.
  • 14. Best Practice for Writing Test Classes cont….. • If you find a bug, write a test to expose it before you fix it • Shoot for 100% coverage – Try to test everything – It’s not always fun or even possible, but try • Don’t rely on Today() – If you are using dates in your code, don’t build your dates on Today() – Use Date.newInstance(Integer year,Integer month,Integer date) – Use a date in the past
  • 15. Reference • http://www.salesforce.com/us/developer/docs/a pexcode/salesforce_apex_language_reference.pd f • http://gokubi.com/archives/testing-bestpractices • http://www.salesforce.com/us/developer/docs/a pexcode/Content/apex_testing_example.htm • http://www.salesforce.com/us/developer/docs/p ages/Content/pages_controller_error_handling.h tm