SlideShare a Scribd company logo
1 of 30
Introduction to Apex Testing
Salesforce World Tour Boston
Jitendra Zaa
Force.com MVP
@JitendraZaa
http://JitendraZaa.com
• Why do we need unit test
• Getting started with Apex test classes
• Testing Visualforce Controller
• Web services Testing
• Testing Apex Callouts
• Best Practices
• Q&A
Agenda
• Development of robust, error-free code
• As Salesforce is multitenant platform, make sure none of governor limits are hitting
• To deploy code on production, unit tests are required
• Minimum 75% of test coverage is required
• Code coverage = number of unique apex lines executed / total number of lines in trigger , classes
• These excludes comments, test methods
• Unit tests are critical part of Salesforce development as it ensures success
• Provides automated regression testing framework to make sure bug free future development
Why unit test
• Apex code that tests other Apex code
• Annotate class with @isTest
• Class methods (static)
• Defined with testMethod keyword
• Classes defined with @isTest annotation does not count against organization limit of 2MB of Apex
code.
How to write unit test
@isTest
public class myClass {
static testMethod void myTest() {
// Add test method logic using System.assert(), System.assertEquals()
// and System.assertNotEquals() here.
}
}
Sample Code
• Used to test governor limits
• To make sure all Asynchronous code executes when stoptest() method is called
• When startTest() method is called, fresh governor limits are applied until stopTest() is
executed
• startTest() and stopTest() can be called only once in testMethod.
Test.startTest() and Test.stopTest()
trigger OverwriteTestAccountDescriptions on Account (before insert) {
for(Account a: Trigger.new){
if (a.Name.toLowerCase().contains('test')){
a.Description =
'This Account is probably left over from testing. It should probably
be deleted.';
}
}
}
Trigger to be tested
Sample Code
static testMethod void verifyAccountDescriptionsWhereOverwritten(){
// Perform our data preparation.
List<Account> accounts = new List<Account>{};
for(Integer i = 0; i < 200; i++){
Account a = new Account(Name = 'Test Account ' + i);
accounts.add(a);
}
// Start the test, this changes governor limit context to
// that of trigger rather than test.
test.startTest();
Test method to test Trigger
Sample Code
// Insert the Account records that cause the trigger to execute.
insert accounts;
// Stop the test, this changes limit context back to test from trigger.
test.stopTest();
// Query the database for the newly inserted records.
List<Account> insertedAccounts = [SELECT Name, Description
FROM Account
WHERE Id IN&nbsp;:accounts];
// Assert that the Description fields contains the proper value now.
for(Account a&nbsp;: insertedAccounts){
System.assertEquals(
'This Account is probably left over from testing. It should probably
be deleted.',
a.Description);
}
}
Sample Code (cont.)
• By default Apex code runs in system mode
• Permission and record sharing are not taken into consideration
• System.runAs() method helps to change test context to either existing or new user
• System.runAs() can only be used in testMethods
System.runAs()
public class TestRunAs {
public static testMethod void testRunAs() {
// This code runs as the system user
Profile p = [select id from profile where name='Standard User'];
User u = new User(alias = 'standt',
email='standarduser@testorg.com',
emailencodingkey='UTF-8', lastname='Testing',
languagelocalekey='en_US', localesidkey='en_US', profileid = p.Id,
timezonesidkey='America/Los_Angeles',
username='standarduser@testorg.com');
System.runAs(u) {
// The following code runs as user 'u'
System.debug('Current User: ' + UserInfo.getUserName());
System.debug('Current Profile: ' + UserInfo.getProfileId()); }
// Run some code that checks record sharing
}
}
Sample Code
• Use TestVisible annotation to allow Test methods to access private or protected members of another
class
• These members can be methods , member variables or inner classes
@TestVisible
public class TestVisibleExample {
// Private member variable
@TestVisible private static Integer recordNumber = 1;
// Private method
@TestVisible private static void updateRecord(String name) {
// Do something
}
}
Actual code to Test
Sample Code
@isTest
private class TestVisibleExampleTest {
@isTest static void test1() {
// Access private variable annotated with TestVisible
Integer i = TestVisibleExample.recordNumber;
System.assertEquals(1, i);
// Access private method annotated with TestVisible
TestVisibleExample.updateRecord('RecordName');
// Perform some verification
}
}
Test Method
Sample Code
• Like all Apex classes and Triggers, Visualforce controllers also requires Test methods
• Test methods can automate user interaction by setting query parameter or navigating to different pages
Test Visualforce Controller
public static testMethod void testMyController() {
//Use the PageReference Apex class to instantiate a page
PageReference pageRef = Page.success;
//In this case, the Visualforce page named 'success' is the starting
point of this test method.
Test.setCurrentPage(pageRef);
//Instantiate and construct the controller class.
Thecontroller controller = new Thecontroller();
//Example of calling an Action method. Same as calling any other Apex
method.
String nextPage = controller.save().getUrl();
//Check that the save() method returns the proper URL.
System.assertEquals('/apex/failure?error=noParam', nextPage);
}
Sample Code
• Generated code from WSDL is saved as Apex class and therefore needs to be tested
• By default test methods does not support Web service call outs
• Apex provides the built-in WebServiceMock interface and the Test.setMock method that you can
use to receive fake responses in a test method.
• Instruct the Apex runtime to generate a fake response whenever WebServiceCallout.invoke is
called.
Testing Web Services
@isTest
global class WebServiceMockImpl implements WebServiceMock {
global void doInvoke(
Object stub,
Object request,
Map<String, Object> response,
String endpoint,
String soapAction,
String requestName,
String responseNS,
String responseName,
String responseType) {
docSample.EchoStringResponse_element respElement =
new docSample.EchoStringResponse_element();
respElement.EchoStringResult = 'Mock response';
response.put('response_x', respElement);
}
}
Sample Code
public class WebSvcCallout {
public static String callEchoString(String input) {
docSample.DocSamplePort sample = new docSample.DocSamplePort();
sample.endpoint_x = 'http://api.salesforce.com/foo/bar';
// This invokes the EchoString method in the generated class
String echo = sample.EchoString(input);
return echo;
}
}
Actual code that calls Web service
Sample Code
@isTest
private class WebSvcCalloutTest {
@isTest static void testEchoString() {
// This causes a fake response to be generated
Test.setMock(WebServiceMock.class, new WebServiceMockImpl());
// Call the method that invokes a callout
String output = WebSvcCallout.callEchoString('Hello World!');
// Verify that a fake result is returned
System.assertEquals('Mock response', output);
}
}
Test class to test Web service response
Sample Code
• Apex has ability to call external Web services like Amazon, Facebook or any other Web service.
• Salesforce does not has any control over response of external Web services.
• Apex callouts can be tested either using HttpCalloutMock interface or using Static Resources.
• HttpCalloutMock Is used to generate fake HttpResponse for testing purpose.
Testing Apex Callouts
@isTest
global class MockHttpResponseGenerator implements HttpCalloutMock {
// Implement this interface method
global HTTPResponse respond(HTTPRequest req) {
// Create a fake response
HttpResponse res = new HttpResponse();
res.setHeader('Content-Type', 'application/json');
res.setBody('{"foo":"bar"}');
res.setStatusCode(200);
return res;
}
}
Implementing HttpCalloutMock interface
Sample Code
public class CalloutClass {
public static HttpResponse getInfoFromExternalService() {
HttpRequest req = new HttpRequest();
req.setEndpoint('http://api.salesforce.com/foo/bar');
req.setMethod('GET');
Http h = new Http();
HttpResponse res = h.send(req);
return res;
}
}
Actual code to be tested
Sample Code
@isTest
private class CalloutClassTest {
@isTest static void testCallout() {
// Set mock callout class
Test.setMock(HttpCalloutMock.class, new MockHttpResponseGenerator());
// This causes a fake response to be sent
// from the class that implements HttpCalloutMock.
HttpResponse res = CalloutClass.getInfoFromExternalService();
// Verify response received contains fake values
String contentType = res.getHeader('Content-Type');
System.assert(contentType == 'application/json');
String actualValue = res.getBody();
String expectedValue = '{"foo":"bar"}';
System.assertEquals(actualValue, expectedValue);
System.assertEquals(200, res.getStatusCode());
}
}
Complete Test methods
Sample Code
• Test methods take no arguments, commit no data to the database, and cannot send any emails.
• Strive for 100% code coverage. Do not focus on the 75% requirement.
• Write portable test methods and do not hardcode any Id or do not rely on some existing data.
• If possible don’t use seeAllData=true annotation
• Use System.assert methods to prove that code behaves properly.
• In the case of conditional logic (including ternary operators), execute each branch of code logic.
• Use the runAs method to test your application in different user contexts.
• Exercise bulk trigger functionality—use at least 20 records in your tests.
Best Practices
• Using static resource to mock Apex callout response
• Apex Test methods Best practices
Other resources
Go though Apex Testing module of Trailhead and earn your badge
Trailhead
Thank you

More Related Content

What's hot

Introduction to blazemeter and jmeter
Introduction to blazemeter and jmeterIntroduction to blazemeter and jmeter
Introduction to blazemeter and jmeterb4usolution .
 
Best Practices for Test Case Writing
Best Practices for Test Case WritingBest Practices for Test Case Writing
Best Practices for Test Case WritingSarah Goldberg
 
Performance Testing from Scratch + JMeter intro
Performance Testing from Scratch + JMeter introPerformance Testing from Scratch + JMeter intro
Performance Testing from Scratch + JMeter introMykola Kovsh
 
38475471 qa-and-software-testing-interview-questions-and-answers
38475471 qa-and-software-testing-interview-questions-and-answers38475471 qa-and-software-testing-interview-questions-and-answers
38475471 qa-and-software-testing-interview-questions-and-answersMaria FutureThoughts
 
01 software test engineering (manual testing)
01 software test engineering (manual testing)01 software test engineering (manual testing)
01 software test engineering (manual testing)Siddireddy Balu
 
Performance testing : An Overview
Performance testing : An OverviewPerformance testing : An Overview
Performance testing : An Overviewsharadkjain
 
An Introduction to Performance Testing
An Introduction to Performance TestingAn Introduction to Performance Testing
An Introduction to Performance TestingSWAAM Tech
 
Performance testing jmeter
Performance testing jmeterPerformance testing jmeter
Performance testing jmeterBhojan Rajan
 
JUnit & Mockito, first steps
JUnit & Mockito, first stepsJUnit & Mockito, first steps
JUnit & Mockito, first stepsRenato Primavera
 
Building Event Driven (Micro)services with Apache Kafka
Building Event Driven (Micro)services with Apache KafkaBuilding Event Driven (Micro)services with Apache Kafka
Building Event Driven (Micro)services with Apache KafkaGuido Schmutz
 
우리 제품의 검증 프로세스 소개 자료
우리 제품의 검증 프로세스 소개 자료 우리 제품의 검증 프로세스 소개 자료
우리 제품의 검증 프로세스 소개 자료 SangIn Choung
 
Testing Tool Evaluation Criteria
Testing Tool Evaluation CriteriaTesting Tool Evaluation Criteria
Testing Tool Evaluation Criteriabasma_iti_1984
 

What's hot (20)

Test automation process
Test automation processTest automation process
Test automation process
 
Introduction to blazemeter and jmeter
Introduction to blazemeter and jmeterIntroduction to blazemeter and jmeter
Introduction to blazemeter and jmeter
 
Best Practices for Test Case Writing
Best Practices for Test Case WritingBest Practices for Test Case Writing
Best Practices for Test Case Writing
 
Performance Testing from Scratch + JMeter intro
Performance Testing from Scratch + JMeter introPerformance Testing from Scratch + JMeter intro
Performance Testing from Scratch + JMeter intro
 
Introducing AWS Device Farm
Introducing AWS Device FarmIntroducing AWS Device Farm
Introducing AWS Device Farm
 
38475471 qa-and-software-testing-interview-questions-and-answers
38475471 qa-and-software-testing-interview-questions-and-answers38475471 qa-and-software-testing-interview-questions-and-answers
38475471 qa-and-software-testing-interview-questions-and-answers
 
JMeter
JMeterJMeter
JMeter
 
01 software test engineering (manual testing)
01 software test engineering (manual testing)01 software test engineering (manual testing)
01 software test engineering (manual testing)
 
Performance testing : An Overview
Performance testing : An OverviewPerformance testing : An Overview
Performance testing : An Overview
 
An Introduction to Performance Testing
An Introduction to Performance TestingAn Introduction to Performance Testing
An Introduction to Performance Testing
 
Performance testing jmeter
Performance testing jmeterPerformance testing jmeter
Performance testing jmeter
 
Spring Core
Spring CoreSpring Core
Spring Core
 
(ARC307) Infrastructure as Code
(ARC307) Infrastructure as Code(ARC307) Infrastructure as Code
(ARC307) Infrastructure as Code
 
JUnit & Mockito, first steps
JUnit & Mockito, first stepsJUnit & Mockito, first steps
JUnit & Mockito, first steps
 
Springboot Microservices
Springboot MicroservicesSpringboot Microservices
Springboot Microservices
 
Building Event Driven (Micro)services with Apache Kafka
Building Event Driven (Micro)services with Apache KafkaBuilding Event Driven (Micro)services with Apache Kafka
Building Event Driven (Micro)services with Apache Kafka
 
우리 제품의 검증 프로세스 소개 자료
우리 제품의 검증 프로세스 소개 자료 우리 제품의 검증 프로세스 소개 자료
우리 제품의 검증 프로세스 소개 자료
 
Testing Tool Evaluation Criteria
Testing Tool Evaluation CriteriaTesting Tool Evaluation Criteria
Testing Tool Evaluation Criteria
 
Automation With A Tool Demo
Automation With A Tool DemoAutomation With A Tool Demo
Automation With A Tool Demo
 
Infrastructure as Code (IaC)
Infrastructure as Code (IaC)Infrastructure as Code (IaC)
Infrastructure as Code (IaC)
 

Viewers also liked

Salesforce Lightning workshop Hartford - 12 March
Salesforce Lightning workshop Hartford - 12 MarchSalesforce Lightning workshop Hartford - 12 March
Salesforce Lightning workshop Hartford - 12 MarchJitendra Zaa
 
Create Salesforce online IDE in 30 minutes
Create Salesforce online IDE in 30 minutesCreate Salesforce online IDE in 30 minutes
Create Salesforce online IDE in 30 minutesJitendra Zaa
 
Deploy Node.js application in Heroku using Eclipse
Deploy Node.js application in Heroku using EclipseDeploy Node.js application in Heroku using Eclipse
Deploy Node.js application in Heroku using EclipseJitendra Zaa
 
Intro to Apex - Salesforce Force Friday Webinar
Intro to Apex - Salesforce Force Friday Webinar Intro to Apex - Salesforce Force Friday Webinar
Intro to Apex - Salesforce Force Friday Webinar Abhinav Gupta
 
Performance Monitoring and Testing in the Salesforce Cloud
Performance Monitoring and Testing in the Salesforce CloudPerformance Monitoring and Testing in the Salesforce Cloud
Performance Monitoring and Testing in the Salesforce CloudSalesforce Developers
 
Crossbrowser Testing at Salesforce Analytics
Crossbrowser Testing at Salesforce AnalyticsCrossbrowser Testing at Salesforce Analytics
Crossbrowser Testing at Salesforce AnalyticsSalesforce Engineering
 
Introduction to bower
Introduction to bowerIntroduction to bower
Introduction to bowerJitendra Zaa
 
Salesforce winter 16 release
Salesforce winter 16 releaseSalesforce winter 16 release
Salesforce winter 16 releaseJitendra Zaa
 
Practical approach for testing your software with php unit
Practical approach for testing your software with php unitPractical approach for testing your software with php unit
Practical approach for testing your software with php unitMario Bittencourt
 
software testing for beginners
software testing for beginnerssoftware testing for beginners
software testing for beginnersBharathi Ashok
 
software testing methodologies
software testing methodologiessoftware testing methodologies
software testing methodologiesJhonny Jhon
 
5 Steps to Usability Testing Success with Salesforce and Beyond!
5 Steps to Usability Testing Success with Salesforce and Beyond!5 Steps to Usability Testing Success with Salesforce and Beyond!
5 Steps to Usability Testing Success with Salesforce and Beyond!Missy Longshore
 
Spring '13 Release Developer Preview Webinar
Spring '13 Release Developer Preview WebinarSpring '13 Release Developer Preview Webinar
Spring '13 Release Developer Preview WebinarSalesforce Developers
 
node.js app deploy to heroku PaaS
node.js app deploy to heroku PaaSnode.js app deploy to heroku PaaS
node.js app deploy to heroku PaaSCaesar Chi
 
Quality Testing and Agile at Salesforce
Quality Testing and Agile at Salesforce Quality Testing and Agile at Salesforce
Quality Testing and Agile at Salesforce Salesforce Engineering
 
Build Reliable Asynchronous Code with Queueable Apex
Build Reliable Asynchronous Code with Queueable ApexBuild Reliable Asynchronous Code with Queueable Apex
Build Reliable Asynchronous Code with Queueable ApexSalesforce Developers
 

Viewers also liked (20)

Salesforce Lightning workshop Hartford - 12 March
Salesforce Lightning workshop Hartford - 12 MarchSalesforce Lightning workshop Hartford - 12 March
Salesforce Lightning workshop Hartford - 12 March
 
Create Salesforce online IDE in 30 minutes
Create Salesforce online IDE in 30 minutesCreate Salesforce online IDE in 30 minutes
Create Salesforce online IDE in 30 minutes
 
Deploy Node.js application in Heroku using Eclipse
Deploy Node.js application in Heroku using EclipseDeploy Node.js application in Heroku using Eclipse
Deploy Node.js application in Heroku using Eclipse
 
Intro to Apex - Salesforce Force Friday Webinar
Intro to Apex - Salesforce Force Friday Webinar Intro to Apex - Salesforce Force Friday Webinar
Intro to Apex - Salesforce Force Friday Webinar
 
Performance Monitoring and Testing in the Salesforce Cloud
Performance Monitoring and Testing in the Salesforce CloudPerformance Monitoring and Testing in the Salesforce Cloud
Performance Monitoring and Testing in the Salesforce Cloud
 
Best Practices for Testing in salesforce.com
Best Practices for Testing in salesforce.comBest Practices for Testing in salesforce.com
Best Practices for Testing in salesforce.com
 
Crossbrowser Testing at Salesforce Analytics
Crossbrowser Testing at Salesforce AnalyticsCrossbrowser Testing at Salesforce Analytics
Crossbrowser Testing at Salesforce Analytics
 
Introduction to bower
Introduction to bowerIntroduction to bower
Introduction to bower
 
Salesforce winter 16 release
Salesforce winter 16 releaseSalesforce winter 16 release
Salesforce winter 16 release
 
Practical approach for testing your software with php unit
Practical approach for testing your software with php unitPractical approach for testing your software with php unit
Practical approach for testing your software with php unit
 
Apex Testing Best Practices
Apex Testing Best PracticesApex Testing Best Practices
Apex Testing Best Practices
 
software testing for beginners
software testing for beginnerssoftware testing for beginners
software testing for beginners
 
software testing methodologies
software testing methodologiessoftware testing methodologies
software testing methodologies
 
5 Steps to Usability Testing Success with Salesforce and Beyond!
5 Steps to Usability Testing Success with Salesforce and Beyond!5 Steps to Usability Testing Success with Salesforce and Beyond!
5 Steps to Usability Testing Success with Salesforce and Beyond!
 
Testing methodology
Testing methodologyTesting methodology
Testing methodology
 
Spring '13 Release Developer Preview Webinar
Spring '13 Release Developer Preview WebinarSpring '13 Release Developer Preview Webinar
Spring '13 Release Developer Preview Webinar
 
node.js app deploy to heroku PaaS
node.js app deploy to heroku PaaSnode.js app deploy to heroku PaaS
node.js app deploy to heroku PaaS
 
Quality Testing and Agile at Salesforce
Quality Testing and Agile at Salesforce Quality Testing and Agile at Salesforce
Quality Testing and Agile at Salesforce
 
Build Reliable Asynchronous Code with Queueable Apex
Build Reliable Asynchronous Code with Queueable ApexBuild Reliable Asynchronous Code with Queueable Apex
Build Reliable Asynchronous Code with Queueable Apex
 
Apex Nirvana
Apex NirvanaApex Nirvana
Apex Nirvana
 

Similar to Apex Testing and Best Practices

Pragmatic unittestingwithj unit
Pragmatic unittestingwithj unitPragmatic unittestingwithj unit
Pragmatic unittestingwithj unitliminescence
 
Test Driven Development with PHPUnit
Test Driven Development with PHPUnitTest Driven Development with PHPUnit
Test Driven Development with PHPUnitMindfire Solutions
 
Test in action week 2
Test in action   week 2Test in action   week 2
Test in action week 2Yi-Huan Chan
 
An introduction to apex code test methods developer.force
An introduction to apex code test methods   developer.forceAn introduction to apex code test methods   developer.force
An introduction to apex code test methods developer.forcesendmail2cherukuri
 
Getting to Grips with SilverStripe Testing
Getting to Grips with SilverStripe TestingGetting to Grips with SilverStripe Testing
Getting to Grips with SilverStripe TestingMark Rickerby
 
How to write clean tests
How to write clean testsHow to write clean tests
How to write clean testsDanylenko Max
 
Enhanced Web Service Testing: A Better Mock Structure
Enhanced Web Service Testing: A Better Mock StructureEnhanced Web Service Testing: A Better Mock Structure
Enhanced Web Service Testing: A Better Mock StructureSalesforce Developers
 
Test Driven Development with JavaFX
Test Driven Development with JavaFXTest Driven Development with JavaFX
Test Driven Development with JavaFXHendrik Ebbers
 
Testing Java Code Effectively
Testing Java Code EffectivelyTesting Java Code Effectively
Testing Java Code EffectivelyAndres Almiray
 
We Are All Testers Now: The Testing Pyramid and Front-End Development
We Are All Testers Now: The Testing Pyramid and Front-End DevelopmentWe Are All Testers Now: The Testing Pyramid and Front-End Development
We Are All Testers Now: The Testing Pyramid and Front-End DevelopmentAll Things Open
 
Developer testing 101: Become a Testing Fanatic
Developer testing 101: Become a Testing FanaticDeveloper testing 101: Become a Testing Fanatic
Developer testing 101: Become a Testing FanaticLB Denker
 
Code Kata: String Calculator in Flex
Code Kata: String Calculator in FlexCode Kata: String Calculator in Flex
Code Kata: String Calculator in FlexChris Farrell
 
SQL Server 2005 CLR Integration
SQL Server 2005 CLR IntegrationSQL Server 2005 CLR Integration
SQL Server 2005 CLR Integrationwebhostingguy
 
Spring 3: What's New
Spring 3: What's NewSpring 3: What's New
Spring 3: What's NewTed Pennings
 

Similar to Apex Testing and Best Practices (20)

Pragmatic unittestingwithj unit
Pragmatic unittestingwithj unitPragmatic unittestingwithj unit
Pragmatic unittestingwithj unit
 
Test Driven Development with PHPUnit
Test Driven Development with PHPUnitTest Driven Development with PHPUnit
Test Driven Development with PHPUnit
 
Test in action week 2
Test in action   week 2Test in action   week 2
Test in action week 2
 
Tdd iPhone For Dummies
Tdd iPhone For DummiesTdd iPhone For Dummies
Tdd iPhone For Dummies
 
An introduction to apex code test methods developer.force
An introduction to apex code test methods   developer.forceAn introduction to apex code test methods   developer.force
An introduction to apex code test methods developer.force
 
Getting to Grips with SilverStripe Testing
Getting to Grips with SilverStripe TestingGetting to Grips with SilverStripe Testing
Getting to Grips with SilverStripe Testing
 
How to write clean tests
How to write clean testsHow to write clean tests
How to write clean tests
 
ERRest
ERRestERRest
ERRest
 
Enhanced Web Service Testing: A Better Mock Structure
Enhanced Web Service Testing: A Better Mock StructureEnhanced Web Service Testing: A Better Mock Structure
Enhanced Web Service Testing: A Better Mock Structure
 
Test Driven Development with JavaFX
Test Driven Development with JavaFXTest Driven Development with JavaFX
Test Driven Development with JavaFX
 
Testing Java Code Effectively
Testing Java Code EffectivelyTesting Java Code Effectively
Testing Java Code Effectively
 
Unit Testing
Unit TestingUnit Testing
Unit Testing
 
Mxunit
MxunitMxunit
Mxunit
 
We Are All Testers Now: The Testing Pyramid and Front-End Development
We Are All Testers Now: The Testing Pyramid and Front-End DevelopmentWe Are All Testers Now: The Testing Pyramid and Front-End Development
We Are All Testers Now: The Testing Pyramid and Front-End Development
 
Developer testing 101: Become a Testing Fanatic
Developer testing 101: Become a Testing FanaticDeveloper testing 101: Become a Testing Fanatic
Developer testing 101: Become a Testing Fanatic
 
Defending against Injections
Defending against InjectionsDefending against Injections
Defending against Injections
 
Code Kata: String Calculator in Flex
Code Kata: String Calculator in FlexCode Kata: String Calculator in Flex
Code Kata: String Calculator in Flex
 
Design for Testability
Design for TestabilityDesign for Testability
Design for Testability
 
SQL Server 2005 CLR Integration
SQL Server 2005 CLR IntegrationSQL Server 2005 CLR Integration
SQL Server 2005 CLR Integration
 
Spring 3: What's New
Spring 3: What's NewSpring 3: What's New
Spring 3: What's New
 

More from Jitendra Zaa

Episode 13 - Advanced Apex Triggers
Episode 13 - Advanced Apex TriggersEpisode 13 - Advanced Apex Triggers
Episode 13 - Advanced Apex TriggersJitendra Zaa
 
Episode 18 - Asynchronous Apex
Episode 18 - Asynchronous ApexEpisode 18 - Asynchronous Apex
Episode 18 - Asynchronous ApexJitendra Zaa
 
Episode 15 - Basics of Javascript
Episode 15 - Basics of JavascriptEpisode 15 - Basics of Javascript
Episode 15 - Basics of JavascriptJitendra Zaa
 
Episode 23 - Design Pattern 3
Episode 23 - Design Pattern 3Episode 23 - Design Pattern 3
Episode 23 - Design Pattern 3Jitendra Zaa
 
Episode 24 - Live Q&A for getting started with Salesforce
Episode 24 - Live Q&A for getting started with SalesforceEpisode 24 - Live Q&A for getting started with Salesforce
Episode 24 - Live Q&A for getting started with SalesforceJitendra Zaa
 
Episode 22 - Design Pattern 2
Episode 22 - Design Pattern 2Episode 22 - Design Pattern 2
Episode 22 - Design Pattern 2Jitendra Zaa
 
Episode 21 - Design Pattern 1
Episode 21 - Design Pattern 1Episode 21 - Design Pattern 1
Episode 21 - Design Pattern 1Jitendra Zaa
 
Episode 20 - Trigger Frameworks in Salesforce
Episode 20 - Trigger Frameworks in SalesforceEpisode 20 - Trigger Frameworks in Salesforce
Episode 20 - Trigger Frameworks in SalesforceJitendra Zaa
 
Episode 19 - Asynchronous Apex - Batch apex & schedulers
Episode 19 - Asynchronous Apex - Batch apex & schedulersEpisode 19 - Asynchronous Apex - Batch apex & schedulers
Episode 19 - Asynchronous Apex - Batch apex & schedulersJitendra Zaa
 
Episode 17 - Handling Events in Lightning Web Component
Episode 17 - Handling Events in Lightning Web ComponentEpisode 17 - Handling Events in Lightning Web Component
Episode 17 - Handling Events in Lightning Web ComponentJitendra Zaa
 
Episode 16 - Introduction to LWC
Episode 16 - Introduction to LWCEpisode 16 - Introduction to LWC
Episode 16 - Introduction to LWCJitendra Zaa
 
Introduction to mulesoft - Alpharetta Developer Group Meet
Introduction to mulesoft - Alpharetta Developer Group MeetIntroduction to mulesoft - Alpharetta Developer Group Meet
Introduction to mulesoft - Alpharetta Developer Group MeetJitendra Zaa
 
Episode 12 - Basics of Trigger
Episode 12 - Basics of TriggerEpisode 12 - Basics of Trigger
Episode 12 - Basics of TriggerJitendra Zaa
 
Episode 11 building & exposing rest api in salesforce v1.0
Episode 11   building & exposing rest api in salesforce v1.0Episode 11   building & exposing rest api in salesforce v1.0
Episode 11 building & exposing rest api in salesforce v1.0Jitendra Zaa
 
Episode 10 - External Services in Salesforce
Episode 10 - External Services in SalesforceEpisode 10 - External Services in Salesforce
Episode 10 - External Services in SalesforceJitendra Zaa
 
Episode 14 - Basics of HTML for Salesforce
Episode 14 - Basics of HTML for SalesforceEpisode 14 - Basics of HTML for Salesforce
Episode 14 - Basics of HTML for SalesforceJitendra Zaa
 
South East Dreamin 2019
South East Dreamin 2019South East Dreamin 2019
South East Dreamin 2019Jitendra Zaa
 
Episode 9 - Building soap integrations in salesforce
Episode 9 - Building soap integrations  in salesforceEpisode 9 - Building soap integrations  in salesforce
Episode 9 - Building soap integrations in salesforceJitendra Zaa
 
Episode 8 - Path To Code - Integrate Salesforce with external system using R...
Episode 8  - Path To Code - Integrate Salesforce with external system using R...Episode 8  - Path To Code - Integrate Salesforce with external system using R...
Episode 8 - Path To Code - Integrate Salesforce with external system using R...Jitendra Zaa
 
Episode 6 - DML, Transaction and Error handling in Salesforce
Episode 6 - DML, Transaction and Error handling in SalesforceEpisode 6 - DML, Transaction and Error handling in Salesforce
Episode 6 - DML, Transaction and Error handling in SalesforceJitendra Zaa
 

More from Jitendra Zaa (20)

Episode 13 - Advanced Apex Triggers
Episode 13 - Advanced Apex TriggersEpisode 13 - Advanced Apex Triggers
Episode 13 - Advanced Apex Triggers
 
Episode 18 - Asynchronous Apex
Episode 18 - Asynchronous ApexEpisode 18 - Asynchronous Apex
Episode 18 - Asynchronous Apex
 
Episode 15 - Basics of Javascript
Episode 15 - Basics of JavascriptEpisode 15 - Basics of Javascript
Episode 15 - Basics of Javascript
 
Episode 23 - Design Pattern 3
Episode 23 - Design Pattern 3Episode 23 - Design Pattern 3
Episode 23 - Design Pattern 3
 
Episode 24 - Live Q&A for getting started with Salesforce
Episode 24 - Live Q&A for getting started with SalesforceEpisode 24 - Live Q&A for getting started with Salesforce
Episode 24 - Live Q&A for getting started with Salesforce
 
Episode 22 - Design Pattern 2
Episode 22 - Design Pattern 2Episode 22 - Design Pattern 2
Episode 22 - Design Pattern 2
 
Episode 21 - Design Pattern 1
Episode 21 - Design Pattern 1Episode 21 - Design Pattern 1
Episode 21 - Design Pattern 1
 
Episode 20 - Trigger Frameworks in Salesforce
Episode 20 - Trigger Frameworks in SalesforceEpisode 20 - Trigger Frameworks in Salesforce
Episode 20 - Trigger Frameworks in Salesforce
 
Episode 19 - Asynchronous Apex - Batch apex & schedulers
Episode 19 - Asynchronous Apex - Batch apex & schedulersEpisode 19 - Asynchronous Apex - Batch apex & schedulers
Episode 19 - Asynchronous Apex - Batch apex & schedulers
 
Episode 17 - Handling Events in Lightning Web Component
Episode 17 - Handling Events in Lightning Web ComponentEpisode 17 - Handling Events in Lightning Web Component
Episode 17 - Handling Events in Lightning Web Component
 
Episode 16 - Introduction to LWC
Episode 16 - Introduction to LWCEpisode 16 - Introduction to LWC
Episode 16 - Introduction to LWC
 
Introduction to mulesoft - Alpharetta Developer Group Meet
Introduction to mulesoft - Alpharetta Developer Group MeetIntroduction to mulesoft - Alpharetta Developer Group Meet
Introduction to mulesoft - Alpharetta Developer Group Meet
 
Episode 12 - Basics of Trigger
Episode 12 - Basics of TriggerEpisode 12 - Basics of Trigger
Episode 12 - Basics of Trigger
 
Episode 11 building & exposing rest api in salesforce v1.0
Episode 11   building & exposing rest api in salesforce v1.0Episode 11   building & exposing rest api in salesforce v1.0
Episode 11 building & exposing rest api in salesforce v1.0
 
Episode 10 - External Services in Salesforce
Episode 10 - External Services in SalesforceEpisode 10 - External Services in Salesforce
Episode 10 - External Services in Salesforce
 
Episode 14 - Basics of HTML for Salesforce
Episode 14 - Basics of HTML for SalesforceEpisode 14 - Basics of HTML for Salesforce
Episode 14 - Basics of HTML for Salesforce
 
South East Dreamin 2019
South East Dreamin 2019South East Dreamin 2019
South East Dreamin 2019
 
Episode 9 - Building soap integrations in salesforce
Episode 9 - Building soap integrations  in salesforceEpisode 9 - Building soap integrations  in salesforce
Episode 9 - Building soap integrations in salesforce
 
Episode 8 - Path To Code - Integrate Salesforce with external system using R...
Episode 8  - Path To Code - Integrate Salesforce with external system using R...Episode 8  - Path To Code - Integrate Salesforce with external system using R...
Episode 8 - Path To Code - Integrate Salesforce with external system using R...
 
Episode 6 - DML, Transaction and Error handling in Salesforce
Episode 6 - DML, Transaction and Error handling in SalesforceEpisode 6 - DML, Transaction and Error handling in Salesforce
Episode 6 - DML, Transaction and Error handling in Salesforce
 

Recently uploaded

VIP Kolkata Call Girl Kestopur 👉 8250192130 Available With Room
VIP Kolkata Call Girl Kestopur 👉 8250192130  Available With RoomVIP Kolkata Call Girl Kestopur 👉 8250192130  Available With Room
VIP Kolkata Call Girl Kestopur 👉 8250192130 Available With Roomdivyansh0kumar0
 
定制(Management毕业证书)新加坡管理大学毕业证成绩单原版一比一
定制(Management毕业证书)新加坡管理大学毕业证成绩单原版一比一定制(Management毕业证书)新加坡管理大学毕业证成绩单原版一比一
定制(Management毕业证书)新加坡管理大学毕业证成绩单原版一比一Fs
 
Russian Call Girls in Kolkata Samaira 🤌 8250192130 🚀 Vip Call Girls Kolkata
Russian Call Girls in Kolkata Samaira 🤌  8250192130 🚀 Vip Call Girls KolkataRussian Call Girls in Kolkata Samaira 🤌  8250192130 🚀 Vip Call Girls Kolkata
Russian Call Girls in Kolkata Samaira 🤌 8250192130 🚀 Vip Call Girls Kolkataanamikaraghav4
 
Russian Call Girls in Kolkata Ishita 🤌 8250192130 🚀 Vip Call Girls Kolkata
Russian Call Girls in Kolkata Ishita 🤌  8250192130 🚀 Vip Call Girls KolkataRussian Call Girls in Kolkata Ishita 🤌  8250192130 🚀 Vip Call Girls Kolkata
Russian Call Girls in Kolkata Ishita 🤌 8250192130 🚀 Vip Call Girls Kolkataanamikaraghav4
 
Git and Github workshop GDSC MLRITM
Git and Github  workshop GDSC MLRITMGit and Github  workshop GDSC MLRITM
Git and Github workshop GDSC MLRITMgdsc13
 
FULL ENJOY Call Girls In Mayur Vihar Delhi Contact Us 8377087607
FULL ENJOY Call Girls In Mayur Vihar Delhi Contact Us 8377087607FULL ENJOY Call Girls In Mayur Vihar Delhi Contact Us 8377087607
FULL ENJOY Call Girls In Mayur Vihar Delhi Contact Us 8377087607dollysharma2066
 
A Good Girl's Guide to Murder (A Good Girl's Guide to Murder, #1)
A Good Girl's Guide to Murder (A Good Girl's Guide to Murder, #1)A Good Girl's Guide to Murder (A Good Girl's Guide to Murder, #1)
A Good Girl's Guide to Murder (A Good Girl's Guide to Murder, #1)Christopher H Felton
 
定制(CC毕业证书)美国美国社区大学毕业证成绩单原版一比一
定制(CC毕业证书)美国美国社区大学毕业证成绩单原版一比一定制(CC毕业证书)美国美国社区大学毕业证成绩单原版一比一
定制(CC毕业证书)美国美国社区大学毕业证成绩单原版一比一3sw2qly1
 
Call Girls Service Adil Nagar 7001305949 Need escorts Service Pooja Vip
Call Girls Service Adil Nagar 7001305949 Need escorts Service Pooja VipCall Girls Service Adil Nagar 7001305949 Need escorts Service Pooja Vip
Call Girls Service Adil Nagar 7001305949 Need escorts Service Pooja VipCall Girls Lucknow
 
VIP Kolkata Call Girl Salt Lake 👉 8250192130 Available With Room
VIP Kolkata Call Girl Salt Lake 👉 8250192130  Available With RoomVIP Kolkata Call Girl Salt Lake 👉 8250192130  Available With Room
VIP Kolkata Call Girl Salt Lake 👉 8250192130 Available With Roomishabajaj13
 
Packaging the Monolith - PHP Tek 2024 (Breaking it down one bite at a time)
Packaging the Monolith - PHP Tek 2024 (Breaking it down one bite at a time)Packaging the Monolith - PHP Tek 2024 (Breaking it down one bite at a time)
Packaging the Monolith - PHP Tek 2024 (Breaking it down one bite at a time)Dana Luther
 
定制(UAL学位证)英国伦敦艺术大学毕业证成绩单原版一比一
定制(UAL学位证)英国伦敦艺术大学毕业证成绩单原版一比一定制(UAL学位证)英国伦敦艺术大学毕业证成绩单原版一比一
定制(UAL学位证)英国伦敦艺术大学毕业证成绩单原版一比一Fs
 
Call Girls South Delhi Delhi reach out to us at ☎ 9711199012
Call Girls South Delhi Delhi reach out to us at ☎ 9711199012Call Girls South Delhi Delhi reach out to us at ☎ 9711199012
Call Girls South Delhi Delhi reach out to us at ☎ 9711199012rehmti665
 
VIP 7001035870 Find & Meet Hyderabad Call Girls LB Nagar high-profile Call Girl
VIP 7001035870 Find & Meet Hyderabad Call Girls LB Nagar high-profile Call GirlVIP 7001035870 Find & Meet Hyderabad Call Girls LB Nagar high-profile Call Girl
VIP 7001035870 Find & Meet Hyderabad Call Girls LB Nagar high-profile Call Girladitipandeya
 
Sushant Golf City / best call girls in Lucknow | Service-oriented sexy call g...
Sushant Golf City / best call girls in Lucknow | Service-oriented sexy call g...Sushant Golf City / best call girls in Lucknow | Service-oriented sexy call g...
Sushant Golf City / best call girls in Lucknow | Service-oriented sexy call g...akbard9823
 

Recently uploaded (20)

VIP Kolkata Call Girl Kestopur 👉 8250192130 Available With Room
VIP Kolkata Call Girl Kestopur 👉 8250192130  Available With RoomVIP Kolkata Call Girl Kestopur 👉 8250192130  Available With Room
VIP Kolkata Call Girl Kestopur 👉 8250192130 Available With Room
 
定制(Management毕业证书)新加坡管理大学毕业证成绩单原版一比一
定制(Management毕业证书)新加坡管理大学毕业证成绩单原版一比一定制(Management毕业证书)新加坡管理大学毕业证成绩单原版一比一
定制(Management毕业证书)新加坡管理大学毕业证成绩单原版一比一
 
Russian Call Girls in Kolkata Samaira 🤌 8250192130 🚀 Vip Call Girls Kolkata
Russian Call Girls in Kolkata Samaira 🤌  8250192130 🚀 Vip Call Girls KolkataRussian Call Girls in Kolkata Samaira 🤌  8250192130 🚀 Vip Call Girls Kolkata
Russian Call Girls in Kolkata Samaira 🤌 8250192130 🚀 Vip Call Girls Kolkata
 
Russian Call Girls in Kolkata Ishita 🤌 8250192130 🚀 Vip Call Girls Kolkata
Russian Call Girls in Kolkata Ishita 🤌  8250192130 🚀 Vip Call Girls KolkataRussian Call Girls in Kolkata Ishita 🤌  8250192130 🚀 Vip Call Girls Kolkata
Russian Call Girls in Kolkata Ishita 🤌 8250192130 🚀 Vip Call Girls Kolkata
 
Model Call Girl in Jamuna Vihar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in  Jamuna Vihar Delhi reach out to us at 🔝9953056974🔝Model Call Girl in  Jamuna Vihar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Jamuna Vihar Delhi reach out to us at 🔝9953056974🔝
 
Rohini Sector 26 Call Girls Delhi 9999965857 @Sabina Saikh No Advance
Rohini Sector 26 Call Girls Delhi 9999965857 @Sabina Saikh No AdvanceRohini Sector 26 Call Girls Delhi 9999965857 @Sabina Saikh No Advance
Rohini Sector 26 Call Girls Delhi 9999965857 @Sabina Saikh No Advance
 
Git and Github workshop GDSC MLRITM
Git and Github  workshop GDSC MLRITMGit and Github  workshop GDSC MLRITM
Git and Github workshop GDSC MLRITM
 
sasti delhi Call Girls in munirka 🔝 9953056974 🔝 escort Service-
sasti delhi Call Girls in munirka 🔝 9953056974 🔝 escort Service-sasti delhi Call Girls in munirka 🔝 9953056974 🔝 escort Service-
sasti delhi Call Girls in munirka 🔝 9953056974 🔝 escort Service-
 
FULL ENJOY Call Girls In Mayur Vihar Delhi Contact Us 8377087607
FULL ENJOY Call Girls In Mayur Vihar Delhi Contact Us 8377087607FULL ENJOY Call Girls In Mayur Vihar Delhi Contact Us 8377087607
FULL ENJOY Call Girls In Mayur Vihar Delhi Contact Us 8377087607
 
A Good Girl's Guide to Murder (A Good Girl's Guide to Murder, #1)
A Good Girl's Guide to Murder (A Good Girl's Guide to Murder, #1)A Good Girl's Guide to Murder (A Good Girl's Guide to Murder, #1)
A Good Girl's Guide to Murder (A Good Girl's Guide to Murder, #1)
 
定制(CC毕业证书)美国美国社区大学毕业证成绩单原版一比一
定制(CC毕业证书)美国美国社区大学毕业证成绩单原版一比一定制(CC毕业证书)美国美国社区大学毕业证成绩单原版一比一
定制(CC毕业证书)美国美国社区大学毕业证成绩单原版一比一
 
Call Girls Service Adil Nagar 7001305949 Need escorts Service Pooja Vip
Call Girls Service Adil Nagar 7001305949 Need escorts Service Pooja VipCall Girls Service Adil Nagar 7001305949 Need escorts Service Pooja Vip
Call Girls Service Adil Nagar 7001305949 Need escorts Service Pooja Vip
 
VIP Kolkata Call Girl Salt Lake 👉 8250192130 Available With Room
VIP Kolkata Call Girl Salt Lake 👉 8250192130  Available With RoomVIP Kolkata Call Girl Salt Lake 👉 8250192130  Available With Room
VIP Kolkata Call Girl Salt Lake 👉 8250192130 Available With Room
 
Packaging the Monolith - PHP Tek 2024 (Breaking it down one bite at a time)
Packaging the Monolith - PHP Tek 2024 (Breaking it down one bite at a time)Packaging the Monolith - PHP Tek 2024 (Breaking it down one bite at a time)
Packaging the Monolith - PHP Tek 2024 (Breaking it down one bite at a time)
 
young call girls in Uttam Nagar🔝 9953056974 🔝 Delhi escort Service
young call girls in Uttam Nagar🔝 9953056974 🔝 Delhi escort Serviceyoung call girls in Uttam Nagar🔝 9953056974 🔝 Delhi escort Service
young call girls in Uttam Nagar🔝 9953056974 🔝 Delhi escort Service
 
Call Girls Service Dwarka @9999965857 Delhi 🫦 No Advance VVIP 🍎 SERVICE
Call Girls Service Dwarka @9999965857 Delhi 🫦 No Advance  VVIP 🍎 SERVICECall Girls Service Dwarka @9999965857 Delhi 🫦 No Advance  VVIP 🍎 SERVICE
Call Girls Service Dwarka @9999965857 Delhi 🫦 No Advance VVIP 🍎 SERVICE
 
定制(UAL学位证)英国伦敦艺术大学毕业证成绩单原版一比一
定制(UAL学位证)英国伦敦艺术大学毕业证成绩单原版一比一定制(UAL学位证)英国伦敦艺术大学毕业证成绩单原版一比一
定制(UAL学位证)英国伦敦艺术大学毕业证成绩单原版一比一
 
Call Girls South Delhi Delhi reach out to us at ☎ 9711199012
Call Girls South Delhi Delhi reach out to us at ☎ 9711199012Call Girls South Delhi Delhi reach out to us at ☎ 9711199012
Call Girls South Delhi Delhi reach out to us at ☎ 9711199012
 
VIP 7001035870 Find & Meet Hyderabad Call Girls LB Nagar high-profile Call Girl
VIP 7001035870 Find & Meet Hyderabad Call Girls LB Nagar high-profile Call GirlVIP 7001035870 Find & Meet Hyderabad Call Girls LB Nagar high-profile Call Girl
VIP 7001035870 Find & Meet Hyderabad Call Girls LB Nagar high-profile Call Girl
 
Sushant Golf City / best call girls in Lucknow | Service-oriented sexy call g...
Sushant Golf City / best call girls in Lucknow | Service-oriented sexy call g...Sushant Golf City / best call girls in Lucknow | Service-oriented sexy call g...
Sushant Golf City / best call girls in Lucknow | Service-oriented sexy call g...
 

Apex Testing and Best Practices

  • 1. Introduction to Apex Testing Salesforce World Tour Boston
  • 3.
  • 4. • Why do we need unit test • Getting started with Apex test classes • Testing Visualforce Controller • Web services Testing • Testing Apex Callouts • Best Practices • Q&A Agenda
  • 5. • Development of robust, error-free code • As Salesforce is multitenant platform, make sure none of governor limits are hitting • To deploy code on production, unit tests are required • Minimum 75% of test coverage is required • Code coverage = number of unique apex lines executed / total number of lines in trigger , classes • These excludes comments, test methods • Unit tests are critical part of Salesforce development as it ensures success • Provides automated regression testing framework to make sure bug free future development Why unit test
  • 6. • Apex code that tests other Apex code • Annotate class with @isTest • Class methods (static) • Defined with testMethod keyword • Classes defined with @isTest annotation does not count against organization limit of 2MB of Apex code. How to write unit test
  • 7. @isTest public class myClass { static testMethod void myTest() { // Add test method logic using System.assert(), System.assertEquals() // and System.assertNotEquals() here. } } Sample Code
  • 8. • Used to test governor limits • To make sure all Asynchronous code executes when stoptest() method is called • When startTest() method is called, fresh governor limits are applied until stopTest() is executed • startTest() and stopTest() can be called only once in testMethod. Test.startTest() and Test.stopTest()
  • 9. trigger OverwriteTestAccountDescriptions on Account (before insert) { for(Account a: Trigger.new){ if (a.Name.toLowerCase().contains('test')){ a.Description = 'This Account is probably left over from testing. It should probably be deleted.'; } } } Trigger to be tested Sample Code
  • 10. static testMethod void verifyAccountDescriptionsWhereOverwritten(){ // Perform our data preparation. List<Account> accounts = new List<Account>{}; for(Integer i = 0; i < 200; i++){ Account a = new Account(Name = 'Test Account ' + i); accounts.add(a); } // Start the test, this changes governor limit context to // that of trigger rather than test. test.startTest(); Test method to test Trigger Sample Code
  • 11. // Insert the Account records that cause the trigger to execute. insert accounts; // Stop the test, this changes limit context back to test from trigger. test.stopTest(); // Query the database for the newly inserted records. List<Account> insertedAccounts = [SELECT Name, Description FROM Account WHERE Id IN&nbsp;:accounts]; // Assert that the Description fields contains the proper value now. for(Account a&nbsp;: insertedAccounts){ System.assertEquals( 'This Account is probably left over from testing. It should probably be deleted.', a.Description); } } Sample Code (cont.)
  • 12. • By default Apex code runs in system mode • Permission and record sharing are not taken into consideration • System.runAs() method helps to change test context to either existing or new user • System.runAs() can only be used in testMethods System.runAs()
  • 13. public class TestRunAs { public static testMethod void testRunAs() { // This code runs as the system user Profile p = [select id from profile where name='Standard User']; User u = new User(alias = 'standt', email='standarduser@testorg.com', emailencodingkey='UTF-8', lastname='Testing', languagelocalekey='en_US', localesidkey='en_US', profileid = p.Id, timezonesidkey='America/Los_Angeles', username='standarduser@testorg.com'); System.runAs(u) { // The following code runs as user 'u' System.debug('Current User: ' + UserInfo.getUserName()); System.debug('Current Profile: ' + UserInfo.getProfileId()); } // Run some code that checks record sharing } } Sample Code
  • 14. • Use TestVisible annotation to allow Test methods to access private or protected members of another class • These members can be methods , member variables or inner classes @TestVisible
  • 15. public class TestVisibleExample { // Private member variable @TestVisible private static Integer recordNumber = 1; // Private method @TestVisible private static void updateRecord(String name) { // Do something } } Actual code to Test Sample Code
  • 16. @isTest private class TestVisibleExampleTest { @isTest static void test1() { // Access private variable annotated with TestVisible Integer i = TestVisibleExample.recordNumber; System.assertEquals(1, i); // Access private method annotated with TestVisible TestVisibleExample.updateRecord('RecordName'); // Perform some verification } } Test Method Sample Code
  • 17. • Like all Apex classes and Triggers, Visualforce controllers also requires Test methods • Test methods can automate user interaction by setting query parameter or navigating to different pages Test Visualforce Controller
  • 18. public static testMethod void testMyController() { //Use the PageReference Apex class to instantiate a page PageReference pageRef = Page.success; //In this case, the Visualforce page named 'success' is the starting point of this test method. Test.setCurrentPage(pageRef); //Instantiate and construct the controller class. Thecontroller controller = new Thecontroller(); //Example of calling an Action method. Same as calling any other Apex method. String nextPage = controller.save().getUrl(); //Check that the save() method returns the proper URL. System.assertEquals('/apex/failure?error=noParam', nextPage); } Sample Code
  • 19. • Generated code from WSDL is saved as Apex class and therefore needs to be tested • By default test methods does not support Web service call outs • Apex provides the built-in WebServiceMock interface and the Test.setMock method that you can use to receive fake responses in a test method. • Instruct the Apex runtime to generate a fake response whenever WebServiceCallout.invoke is called. Testing Web Services
  • 20. @isTest global class WebServiceMockImpl implements WebServiceMock { global void doInvoke( Object stub, Object request, Map<String, Object> response, String endpoint, String soapAction, String requestName, String responseNS, String responseName, String responseType) { docSample.EchoStringResponse_element respElement = new docSample.EchoStringResponse_element(); respElement.EchoStringResult = 'Mock response'; response.put('response_x', respElement); } } Sample Code
  • 21. public class WebSvcCallout { public static String callEchoString(String input) { docSample.DocSamplePort sample = new docSample.DocSamplePort(); sample.endpoint_x = 'http://api.salesforce.com/foo/bar'; // This invokes the EchoString method in the generated class String echo = sample.EchoString(input); return echo; } } Actual code that calls Web service Sample Code
  • 22. @isTest private class WebSvcCalloutTest { @isTest static void testEchoString() { // This causes a fake response to be generated Test.setMock(WebServiceMock.class, new WebServiceMockImpl()); // Call the method that invokes a callout String output = WebSvcCallout.callEchoString('Hello World!'); // Verify that a fake result is returned System.assertEquals('Mock response', output); } } Test class to test Web service response Sample Code
  • 23. • Apex has ability to call external Web services like Amazon, Facebook or any other Web service. • Salesforce does not has any control over response of external Web services. • Apex callouts can be tested either using HttpCalloutMock interface or using Static Resources. • HttpCalloutMock Is used to generate fake HttpResponse for testing purpose. Testing Apex Callouts
  • 24. @isTest global class MockHttpResponseGenerator implements HttpCalloutMock { // Implement this interface method global HTTPResponse respond(HTTPRequest req) { // Create a fake response HttpResponse res = new HttpResponse(); res.setHeader('Content-Type', 'application/json'); res.setBody('{"foo":"bar"}'); res.setStatusCode(200); return res; } } Implementing HttpCalloutMock interface Sample Code
  • 25. public class CalloutClass { public static HttpResponse getInfoFromExternalService() { HttpRequest req = new HttpRequest(); req.setEndpoint('http://api.salesforce.com/foo/bar'); req.setMethod('GET'); Http h = new Http(); HttpResponse res = h.send(req); return res; } } Actual code to be tested Sample Code
  • 26. @isTest private class CalloutClassTest { @isTest static void testCallout() { // Set mock callout class Test.setMock(HttpCalloutMock.class, new MockHttpResponseGenerator()); // This causes a fake response to be sent // from the class that implements HttpCalloutMock. HttpResponse res = CalloutClass.getInfoFromExternalService(); // Verify response received contains fake values String contentType = res.getHeader('Content-Type'); System.assert(contentType == 'application/json'); String actualValue = res.getBody(); String expectedValue = '{"foo":"bar"}'; System.assertEquals(actualValue, expectedValue); System.assertEquals(200, res.getStatusCode()); } } Complete Test methods Sample Code
  • 27. • Test methods take no arguments, commit no data to the database, and cannot send any emails. • Strive for 100% code coverage. Do not focus on the 75% requirement. • Write portable test methods and do not hardcode any Id or do not rely on some existing data. • If possible don’t use seeAllData=true annotation • Use System.assert methods to prove that code behaves properly. • In the case of conditional logic (including ternary operators), execute each branch of code logic. • Use the runAs method to test your application in different user contexts. • Exercise bulk trigger functionality—use at least 20 records in your tests. Best Practices
  • 28. • Using static resource to mock Apex callout response • Apex Test methods Best practices Other resources
  • 29. Go though Apex Testing module of Trailhead and earn your badge Trailhead

Editor's Notes

  1. To test methods defined with the future annotation, call the class containing the method in a startTest(), stopTest() code block. All asynchronous calls made after the startTest method are collected by the system. When stopTest is executed, all asynchronous processes are run synchronously. The startTest method does not refresh the context of the test: it adds a context to your test. For example, if your class makes 98 SOQL queries before it calls startTest, and the first significant statement after startTest is a DML statement, the program can now make an additional 100 queries. Once stopTest is called, however, the program goes back into the original context, and can only make 2 additional SOQL queries before reaching the limit of 100.
  2. runAs() does not validate CRUD or Field Level Security permissions.
  3. https://www.salesforce.com/us/developer/docs/apexcode/Content/apex_classes_annotation_testvisible.htm
  4. StaticResourceCalloutMock mock = new StaticResourceCalloutMock(); mock.setStaticResource('myStaticResourceName'); mock.setStatusCode(200); mock.setHeader('Content-Type', 'application/json');   Actual code : public class CalloutStaticClass { public static HttpResponse getInfoFromExternalService(String endpoint) { HttpRequest req = new HttpRequest(); req.setEndpoint(endpoint); req.setMethod('GET'); Http h = new Http(); HttpResponse res = h.send(req); return res; } }   ------------------- @isTest private class CalloutStaticClassTest { @isTest static void testCalloutWithStaticResources() { // Use StaticResourceCalloutMock built-in class to // specify fake response and include response body // in a static resource. StaticResourceCalloutMock mock = new StaticResourceCalloutMock(); mock.setStaticResource('mockResponse'); mock.setStatusCode(200); mock.setHeader('Content-Type', 'application/json'); // Set the mock callout mode Test.setMock(HttpCalloutMock.class, mock); // Call the method that performs the callout HTTPResponse res = CalloutStaticClass.getInfoFromExternalService( 'http://api.salesforce.com/foo/bar'); // Verify response received contains values returned by // the mock response. // This is the content of the static resource. System.assertEquals('{"hah":"fooled you"}', res.getBody()); System.assertEquals(200,res.getStatusCode()); System.assertEquals('application/json', res.getHeader('Content-Type')); } }   ----------- Final Test Methods --------------- @isTest private class CalloutStaticClassTest { @isTest static void testCalloutWithStaticResources() { // Use StaticResourceCalloutMock built-in class to // specify fake response and include response body // in a static resource. StaticResourceCalloutMock mock = new StaticResourceCalloutMock(); mock.setStaticResource('mockResponse'); mock.setStatusCode(200); mock.setHeader('Content-Type', 'application/json'); // Set the mock callout mode Test.setMock(HttpCalloutMock.class, mock); // Call the method that performs the callout HTTPResponse res = CalloutStaticClass.getInfoFromExternalService( 'http://api.salesforce.com/foo/bar'); // Verify response received contains values returned by // the mock response. // This is the content of the static resource. System.assertEquals('{"hah":"fooled you"}', res.getBody()); System.assertEquals(200,res.getStatusCode()); System.assertEquals('application/json', res.getHeader('Content-Type')); } }