How to Write Test Classes in Salesforce
? Summary
This article provides a comprehensive guide to writing test classes in Salesforce. Test classes ensure that your Apex code works as expected and meets Salesforce’s deployment requirements by achieving at least 75% code coverage.
⚙️ What Are Test Classes?
Test classes are written in Apex to verify that your triggers, classes, and other logic behave as expected. They simulate real-world scenarios without affecting actual data.
✅ Benefits of Writing Tests
- Required for deployment to production.
- Help catch bugs early.
- Validate business logic under various conditions.
- Ensure future code changes don’t break existing functionality (regression testing).
? Key Requirements
- Minimum 75% code coverage for deployment.
- All triggers must be tested.
- Positive and negative test cases should be included.
- Use System.assert() statements to validate behavior.
? Basic Structure of a Test Class
@isTest
private class AccountHandlerTest {
@testSetup
static void setupData() {
Account acc = new Account(Name = 'Test Account');
insert acc;
}
@isTest
static void testAccountInsertLogic() {
Contact con = new Contact(FirstName = 'Test', LastName = 'User', AccountId = [SELECT Id FROM Account LIMIT 1].Id);
insert con;
// Validate behavior
Contact insertedCon = [SELECT Description FROM Contact WHERE Id = :con.Id];
System.assertEquals('Created by trigger', insertedCon.Description);
}
}
? Best Practices
1. Use @isTest Annotation
- Marks the class or method as a test.
- Test classes do not count against org Apex limits.
2. Use @testSetup for Common Data
- Creates baseline data that is reused across tests.
- Runs once per test class, improving performance.
3. Test All Logic Paths
- Positive tests (valid inputs).
- Negative tests (invalid inputs, exceptions).
- Edge cases (empty fields, null values).
4. Avoid Using SeeAllData=true
- Tests should be isolated from org data.
- Create all necessary test data programmatically.
5. Use System.assert()
- Validates that actual results match expectations.
6. Cover Bulk Operations
- Simulate inserts/updates with up to 200 records.
7. Test Triggers and Exceptions
- Make sure you cover both success and failure paths.
? Common Patterns
Positive Test
@isTest
static void testValidInsert() {
Account acc = new Account(Name = ‘Test’);
insert acc;
System.assertNotEquals(null, acc.Id);
}
Negative Test (Expecting Failure)
@isTest
static void testInvalidInsert() {
try {
Account acc = new Account(); // Missing required Name
insert acc;
System.assert(false, ‘Insert should have failed’);
} catch (DmlException e) {
System.assert(e.getMessage().contains(‘Name’));
}
}
? Viewing Code Coverage
- Setup > Apex Test Execution
- Developer Console > Test > New Run
- Use Test.run() in Anonymous Apex to run test methods programmatically.
❌ Common Mistakes
| Mistake | Impact | Fix |
|---|---|---|
| Not creating test data | Tests fail or behave unpredictably | Use @testSetup or method-level test data |
Not using System.assert() | Tests don’t verify logic | Always assert expected results |
Overusing SeeAllData=true | Makes tests dependent on real data | Create all required test data in the test class |
| Ignoring exceptions | Can miss logic flaws | Include tests for invalid inputs and error conditions |
| Only testing one record | Doesn’t cover bulk behavior | Simulate large data sets (up to 200 records) |
? Example: Testing a Trigger
@isTest
private class ContactTriggerTest {
@isTest
static void testBeforeInsert() {
Contact c = new Contact(FirstName='John', LastName='Doe');
insert c;
Contact inserted = [SELECT Description FROM Contact WHERE Id = :c.Id];
System.assertEquals('Created by trigger', inserted.Description);
}
}
-
How to
- How to Download and Install Salesforce CLI
- How to Enable Inline Editing in Salesforce
- How to Download and Install Salesforce CLI: A 2026 Guide
- How to Use SOQL and SOSL with Salesforce CLI: A 2025 Guide
- How to Connect Salesforce CLI to a Sandbox or Scratch Org in 2025
- How to Enable Inline Editing in Salesforce: A 2025 Guide
- How to Customize Salesforce Page Layouts for Better Usability in 2025
- How to Set Up Your Pipedrive Account: Easy Step-by-Step Guide
- How to Import and Export Data in Pipedrive: Easy Step-by-Step Guide
- How to Customize Pipelines and Stages in Pipedrive: Easy Step-by-Step Guide
- How to Set Up and Use Custom Fields in Pipedrive: Easy Step-by-Step Guide
- How to Set Up Your First Board in monday.com
- How to Customize Columns and Item Views in monday.com
- How to Import Data into monday.com (Excel, Google Sheets, CSV)
- How to Use List Views and Filters Effectively in Salesforce
- How to Manage Visibility and Permissions in Pipedrive
- How to Use Salesforce Flow to Automate Repetitive Tasks in Salesforce
- How to Perform Bulk Data Updates in Salesforce
- How to Handle Lookup Relationships When Importing Data
- How to Deploy Changes Between Salesforce Sandboxes
- How to Write Test Classes in Salesforce
- How to Use Change Sets Effectively in Salesforce
- How to Debug Apex Errors in Salesforce
- How to Set Up Salesforce Profiles and Permission Sets
- How to Set Up Salesforce with Slack
- How to Use Salesforce AppExchange Effectively
- How to Set Up and Use Multiple Pipelines in Pipedrive
- How to Automate Tasks and Emails in Pipedrive
- How to Use Pipedrive Smart Contact Data
- How to Set Up Activity Reminders and Follow-Ups Automatically in Pipedrive
- How to Automate Lead Assignment in Pipedrive
- How to Connect Your Email to Pipedrive
- How to Set Up Email Templates and Sequences in Pipedrive
- How to Track Email Opens and Link Clicks in Pipedrive
- How to Log Calls and Emails Automatically in Pipedrive
- How to Use Pipedrive Caller and Phone Integrations
- How to Integrate Pipedrive with Gmail and Outlook
- How to Connect Pipedrive to Zapier for Automation
- How to Integrate Pipedrive with Google Sheets
- How to Use the Pipedrive API: A Beginner’s Guide
- How to Integrate Pipedrive with LinkedIn
- How to Forecast Revenue Accurately in Pipedrive
- How to Track Sales Team Performance with Pipedrive Reports
- How to Use Filters and Segmentation for Better Reporting in Pipedrive
- How to Add and Manage Deals in Pipedrive
- How to Set Up Deal Rotting Alerts in Pipedrive
- How to Use Deal Probability and Weighted Forecasts in Pipedrive
- How to Merge Duplicate Deals and Contacts in Pipedrive
- How to Add and Manage Users in Pipedrive
- How to Set Up Two-Factor Authentication (2FA) in Pipedrive
- How to Use Pipedrive’s LeadBooster Chatbot Effectively
- How to Sync Pipedrive with Your Calendar (Google, Outlook)
- How to Prepare for Pipedrive CRM Certification
- SEO-Driven “How-to” and “Fix” Articles for Pipedrive Users
- How to Fix Email Sync Issues in Pipedrive
- How to Bulk Edit Contacts and Deals in Pipedrive
- How to Recover Deleted Deals or Contacts in Pipedrive
- How to Create a Sales Funnel in Pipedrive
- How to Track the Source of Leads in Pipedrive
- How to Use Tags Effectively in Pipedrive
- How to Create and Manage Project Templates in monday.com
- How to Use Subitems for Better Task Breakdown in monday.com
- How to Set Up Recurring Tasks in monday.com
- How to Use the Timeline, Gantt, and Calendar Views in monday.com
- How to Set Up and Track Milestones in monday.com
- How to Create Custom Automations in monday.com
- How to Integrate monday.com with Slack, Gmail, and Outlook
- How to Use monday.com API: A Beginner’s Guide with Examples
- Monday.com + Jira Integration: How to Sync Tasks
- How to Build Custom Dashboards in monday.com
- How to Monitor Team Workload and Capacity in monday.com
- How to Export Reports and Dashboard Data in monday.com
- How to Use Updates, @Mentions, and Files in Items in monday.com
- How to Manage Notifications and Inbox Overload in monday.com
- How to Collaborate with Guests, Clients, and Freelancers in monday.com
- How to Set Up User Permissions and Roles in monday.com
- How to Use Two-Factor Authentication (2FA) for Enhanced Security in monday.com
- How to Control Access to Sensitive Data in monday.com
- How to Use monday.com for Agile/Scrum Project Management
- Time Tracking in monday.com: How to Use and Report
- How to Create a CRM System in monday.com
- How to Fix Board Loading or Performance Issues in monday.com
- How to Restore Deleted Boards, Items, and Columns in monday.com
- How to Join and Use the monday.com Community Forum
- SEO-Driven ‘How-To’ & ‘Fix’ Articles Based on Search Volume in monday.com
- How to Set Dependencies in monday.com
- How to Create a Kanban Board in monday.com
- How to Duplicate a Board or Template in monday.com
- How to Calculate Values Using Formula Columns in monday.com
- How to Create Dynamic Charts and Graphs in monday.com
- How to Automate Status Changes Based on Due Dates in monday.com
- How to Integrate monday.com with Power BI
- How to Set Up Your Zoho Account and Dashboard
- How to Import Data into Zoho CRM from Excel or CSV
- How to Connect Pipedrive to Other Tools Using Zapier?
- How to Integrate Pipedrive with n8n for Smarter Workflows?
- How to Connect and Sync Pipedrive Using Native Tools?
- How to Integrate Pipedrive with Email & Calendars via Zapier?
- How to Connect Pipedrive Deals to Your Website Forms Using n8n?
- How to Connect Salesforce with Marketing Platforms via Zapier?
- How to Integrate Salesforce with n8n for Automation Streams?
- How to Connect Salesforce Using Native Tools (Flows & APIs)?
- How to Integrate Salesforce Leads into Your CRM with Zapier?
- How to Connect Salesforce Reports to Slack Using n8n?
- How to Connect Zoho CRM with Email & Chat Tools via Zapier?
- How to Integrate Zoho CRM with n8n for Custom Workflows?
- How to Connect Zoho Apps Using Native Tools (Zoho Flow)?
- How to Integrate Zoho CRM and Project Management Tools with Zapier?
- How to Connect Zoho Automations to Third-Party APIs via n8n?
- How to Connect monday.com to Your CRM Using Zapier?
- How to Integrate monday.com with n8n for Advanced Automation?
- How to Connect monday.com Boards Using Native Tools?
- How to Integrate monday.com with Google Workspace via Zapier?
- How to Connect monday.com to Support Tools Using n8n?
- How to Connect ManageEngine to IT & Helpdesk Systems via Zapier?
- How to Create and Manage Sales Pipelines in Zoho CRM
- How to Implement ManageEngine ServiceDesk Plus Step-by-Step
- How to Set Up ITIL-Compliant Workflows in ManageEngine ITSM
- How to Automate Incident Management in ManageEngine?
- How to Configure SLAs and Escalations in ManageEngine?
- How to Integrate ManageEngine ServiceDesk Plus with Active Directory?
- How to Build a Self-Service Portal in ManageEngine?
- How to Create Custom Reports and Dashboards in ManageEngine ServiceDesk Plus
- How to Create Custom Reports and Dashboards in ManageEngine ServiceDesk Plus?
- How to Manage Change and Release Processes in ManageEngine ITSM?
- How to Migrate from Excel or Legacy Help Desk to ManageEngine?
- How to Connect ManageEngine to Third-Party Monitoring Tools?
- How to Create a biBERK Account?
- How to Get Instant Business Insurance Coverage with biBERK?
- How to Choose the Right biBERK Policy for Your Business?
- How to Bundle Policies with biBERK?
- How to Switch to biBERK from Another Insurance Provider?
- How to Get an Accurate Quote from biBERK Commercial Auto Insurance?
- How to Adjust Coverage to Fit Your Budget in biBERK?
- How to Apply Discounts in biBERK Policies?
- How to Compare biBERK Quotes with Other Insurers?
- How to Update Business Information in biBERK?
- How to Renew Your biBERK Policy?
- How to Build a Reliable CMDB in ManageEngine ServiceDesk Plus
- How to Design Approval Workflows in ManageEngine Without Creating Bottlenecks
- How to Automate Incident Routing in ManageEngine ServiceDesk Plus
- How to Plan a Successful ITSM Implementation with ManageEngine
- How to Remove or Replace a Vehicle on Your biBERK Policy
- How to Add or Update Drivers in biBERK
- How to Add a Vehicle to Your biBERK Commercial Auto Policy
- How to Contact biBERK Customer Support
- How to Reduce Insurance Premiums with biBERK
- How to Buy a Policy Online with biBERK
- How to Download Your biBERK Certificate of Insurance (COI)
- How to Add Umbrella Coverage to Your biBERK Policy
- How to Track the Status of Your Claim in biBERK
- What to Do If a Claim Is Rejected in biBERK
- How to Insure Independent Contractors with biBERK
- How to Store and Manage Policy Documents in biBERK Digitally
- How to Conduct a Pipedrive CRM Audit: Signs Your Setup Is Costing You Deals
- How to Set Up Email Sync in Pipedrive
- How to File a Commercial Auto Claim with biBERK
- How to choose coverage limits for biBerk commercial auto insurance
- How to Submit biBERK Supporting Documents for a Claim
- How to Build Custom Pipedrive Dashboards and Reports with Insights
- How to Connect Pipedrive with Google Analytics 4 via API and GTM
- Show Remaining Articles (146) Collapse Articles
-
Guides
- Salesforce Inspector Chrome Extension: A Complete Guide
- How to Generate an API Key in HubSpot: A Step-by-Step Guide
- Salesforce Inspector Chrome Extension: A Complete Guide for 2025
- VS Code Setup for Salesforce Development: Plugins and Best Practices for 2025
- Mass Edit Records in Salesforce: Tools and Methods for 2025
- Salesforce: Quick Actions vs. Global Actions – What’s the Difference?
- Data and API – An Overview
- Using Salesforce REST API: A Beginner’s Guide
- Exporting Salesforce Data: Best Tools and Methods
- Salesforce TDX (TrailblazerDX): Everything You Need to Know
- Apex Triggers: Best Practices and Common Pitfalls
- Understanding Lightning Web Components (LWC) vs. Aura Components
- Security and Permissions
- How Field-Level Security Works in Salesforce
- Best Practices for Salesforce API Security
- What is Shield Encryption and When Do You Need It?
- Integrations and Ecosystem
- Top 5 Salesforce Integrations Every Business Should Consider
- Salesforce and Outlook Integration: Complete Setup Guide
- How to Integrate Salesforce with Google Sheets
- Automation and Workflows in Pipedrive
- Best Practices for Workflow Automation in Pipedrive
- Communication and Email Integration in Pipedrive
- Integrations and API in Pipedrive
- Top 10 Must-Have Pipedrive Integrations
- Best Practices for Connecting Pipedrive with Mailchimp
- How to Create Custom Reports in Pipedrive
- Understanding Pipedrive’s Sales Dashboard and Insights
- Deals and Pipeline Management in Pipedrive
- Best Practices for Pipeline Hygiene and Optimization in Pipedrive
- User Management and Security in Pipedrive
- Understanding Pipedrive Roles, Teams, and Visibility Settings
- GDPR Compliance and Data Security in Pipedrive
- Advanced Tips, Tricks, and Troubleshooting in Pipedrive
- Common Pipedrive Errors and How to Fix Them
- Best Chrome Extensions for Pipedrive Users
- Pipedrive vs. HubSpot CRM: Which One is Better for You?
- Learning and Resources in Pipedrive
- Top Pipedrive Features You’re Probably Not Using (Yet)
- Pipedrive Mobile App: Complete Setup and Tips
- Pipedrive Marketplace: Best Apps to Boost Productivity
- Pipedrive Best Practices for B2B Sales Teams
- Project & Task Management in monday.com
- Automations & Integrations in monday.com
- Best Pre-Built Automations You Should Be Using in monday.com
- Connecting monday.com to Zapier for Advanced Workflows
- Dashboards, Reporting, and Analytics in monday.com
- Understanding Widgets: Chart, Workload, Battery, and More in monday.com
- Creating a Project Budget Tracker in monday.com
- Collaboration and Communication in monday.com
- Best Practices for Team Collaboration in monday.com
- Using monday.com Forms for Internal and External Submissions
- Account, Permissions, and Security in monday.com
- Monday.com: Private vs. Shareable vs. Main Boards – What’s the Difference?
- Understanding monday.com’s Data Protection and Compliance (GDPR, SOC 2, and More)
- Advanced Tips, Use Cases, and Best Practices in monday.com
- Top 10 monday.com Features Most Users Overlook (But Shouldn’t!)
- Event Planning with monday.com: A Complete Workflow
- Troubleshooting and Common Issues in monday.com
- What to Do When Automations Don’t Trigger in monday.com
- Email Integration Errors: Causes and Fixes in monday.com
- Sync Issues with Google Calendar or Outlook in monday.com
- Learning Resources and Community in monday.com
- How to Get Certified with monday.com
- Exploring the monday.com Marketplace for Apps and Extensions
- Upcoming monday.com Webinars and Training Resources
- Monday.com vs. Asana vs. ClickUp: Which Tool Fits Your Workflow?
- Monday.com vs Trello: Which One Should You Choose?
- Getting Started with Zoho: A Beginner’s Guide
- Show Remaining Articles (54) Collapse Articles
-
General Info
- Salesforce TDX (TrailblazerDX): Everything You Need to Know
- Salesforce Tools and Extensions: Boost Your CRM Efficiency in 2025
- Best Chrome Extensions for Salesforce Admins and Developers in 2025
- Understanding Workspaces, Boards, Groups, and Items in monday.com
- monday.com Mobile App: Setup and Tips
- Understanding Salesforce Data Model: Objects, Fields, and Relationships
- Development & Deployment in Salesforce
- Security and Permissions
- Reporting, Analytics, and Forecasting in Pipedrive
- Best monday.com Templates for Marketing, HR, Sales, and Development
- Understanding the Zoho Product Suite (CRM, Books, Mail, Projects, and More)
- Zoho CRM: Sales, Pipelines, and Automation — How Does It All Work?

