100% Free Forever
AI-Powered Learning
Industry Expert Content
Certificates & Badges
Learn At Your Own Pace
Programming

Testing Apex Code

Learn how to write robust Apex test classes, use assertions and mocks, and produce meaningful code coverage that survives real deployments.

Practical ApexIntermediate9 min readJul 10, 2026
Analogies

Why Testing Matters in Apex

Salesforce enforces a hard rule: at least 75% aggregate code coverage across all Apex classes and triggers is required before any deployment to production, and every trigger needs some coverage of its own. But the platform only checks the number — it cannot tell whether your tests actually validate behavior. A test suite that hits 90% coverage with no meaningful assertions is worthless in practice, because it proves the code ran, not that it produced the right result. Every test method also executes inside its own database transaction that Salesforce automatically rolls back afterward, so tests never pollute real org data.

🏏

Cricket analogy: Coverage without assertions is like a batsman facing 90 balls in the nets without anyone checking if he actually hit the shots correctly — Rahul Dravid's technique was judged by shot quality, not ball count.

Structuring Test Classes and Test Methods

A test class is annotated with @isTest and its methods with @isTest (or the older testMethod keyword). Inside a test method, wrap the code under test between Test.startTest() and Test.stopTest() — this resets the governor limit counters for that block and forces any asynchronous work (future methods, queueable jobs, batch Apex) to execute synchronously before stopTest() returns, so you can assert on its results immediately. Shared setup data — accounts, custom settings, users — belongs in a method annotated @testSetup, which runs once before each test method in the class and whose records are automatically rolled back and re-created for isolation between methods.

🏏

Cricket analogy: Test.startTest()/stopTest() is like a fresh Powerplay restriction kicking in — the over count and field placement rules reset so you can measure exactly what happened during that specific phase of play.

apex
@isTest
private class OpportunityServiceTest {

    @testSetup
    static void setup() {
        Account acc = new Account(Name = 'Acme Corp');
        insert acc;

        List<Opportunity> opps = new List<Opportunity>();
        for (Integer i = 0; i < 200; i++) {
            opps.add(new Opportunity(
                Name = 'Deal ' + i,
                AccountId = acc.Id,
                StageName = 'Prospecting',
                CloseDate = Date.today().addDays(30),
                Amount = 1000
            ));
        }
        insert opps;
    }

    @isTest
    static void testBulkStageUpdateAppliesDiscount() {
        List<Opportunity> opps = [SELECT Id, Amount FROM Opportunity];

        Test.startTest();
        OpportunityService.applyClosingDiscount(opps);
        Test.stopTest();

        List<Opportunity> updated = [SELECT Amount FROM Opportunity];
        for (Opportunity o : updated) {
            System.assertEquals(900, o.Amount,
                'Discount of 10% should be applied to each opportunity');
        }
    }

    @isTest
    static void testNullListThrowsIllegalArgumentException() {
        Test.startTest();
        try {
            OpportunityService.applyClosingDiscount(null);
            System.assert(false, 'Expected an exception for null input');
        } catch (IllegalArgumentException e) {
            System.assert(e.getMessage().contains('cannot be null'));
        }
        Test.stopTest();
    }
}

Test Data Isolation and Mocking Callouts

By default, test classes cannot see existing records in the org — the SeeAllData=false behavior — which forces you to create every record your test needs, guaranteeing tests are deterministic regardless of what's in the sandbox or production org. For outbound HTTP callouts, you cannot make real network calls from a test; instead, implement the HttpCalloutMock interface and register it with Test.setMock(HttpCalloutMock.class, new MyMockImpl()) before the callout-triggering code executes, so the callout returns a canned HttpResponse without touching a live endpoint.

🏏

Cricket analogy: It's like practicing in the nets with your own set of balls rather than borrowing from the match day supply — SeeAllData=false forces you to bring (create) everything you need instead of relying on whatever's lying around.

Avoid @isTest(SeeAllData=true) unless you have a specific, unavoidable reason (such as testing against org-wide default sharing settings or certain configuration-only metadata). Relying on existing data makes tests fragile — they can pass in one sandbox and fail in another purely because of differing record counts.

Assertions, Bulk Testing, and Coverage Quality

Modern Apex favors the Assert class (Assert.areEqual, Assert.isTrue, Assert.fail) over the legacy System.assertEquals family because it produces clearer stack traces and integrates better with test result reporting, though both still work. Every test should exercise bulk behavior — insert or update 200+ records inside the tested method, since that is Salesforce's default trigger batch size, and a class that only tests a single record will pass locally but throw a LIMIT_EXCEEDED SOQL or DML error the first time a bulk data load or API integration inserts 200 rows at once. Negative-path tests matter just as much: deliberately trigger validation rule failures, DML exceptions, or custom exceptions and assert that the correct exception type and message surface, using a try/catch with a System.assert(false) fallback in the try block to guarantee the catch was actually reached.

🏏

Cricket analogy: Testing only one record is like a bowler nailing a single perfect yorker in the nets but never testing what happens bowling the 20th over under fatigue in a T20 — bulk load is the real match pressure.

A test method with zero assertions still counts toward your 75% coverage number. This is the single most common anti-pattern reviewers flag: code that merely calls a method and lets the transaction complete, proving nothing about correctness. Every test method should contain at least one meaningful Assert.areEqual, Assert.isTrue, or equivalent check tied to the behavior under test.

  • 75% org-wide coverage is a deployment gate, not a quality metric — assertions are what prove correctness.
  • Test.startTest()/Test.stopTest() resets governor limits and forces async Apex to run synchronously for assertion.
  • @testSetup builds shared baseline data once per test class, re-isolated for every test method.
  • SeeAllData=false by default forces deterministic tests that don't depend on existing org data.
  • Test.setMock with an HttpCalloutMock implementation is required to unit test outbound HTTP callouts.
  • Always test with 200+ records to catch bulk-related governor limit failures before they hit production.
  • Negative tests that assert on thrown exceptions are as important as happy-path assertions.

Practice what you learned

Was this page helpful?

Topics covered

#Programming#ApexSalesforceStudyNotes#TestingApexCode#Testing#Apex#Code#Matters#StudyNotes#SkillVeris#ExamPrep

Frequently Asked Questions

21 categories · pick one to explore

Where can I get free study notes for programming and tech subjects?
SkillVeris offers completely free study notes covering programming and tech subjects, with no signup fees or paywalls. The notes are structured by course and topic, written for quick understanding, and enriched with the Learn Through Hobbies analogy method, so you can revise concepts through cricket, music, gaming, cooking and more.
Are SkillVeris study notes good for exam revision?
Yes, the study notes are designed for efficient revision: each topic answers its heading immediately, keeps explanations concise, and links to related glossary terms and cheat sheets. Students preparing for university exams or certification tests use them as quick revision notes because they distil concepts without the padding of full textbooks.
What subjects do the free study notes cover?
The study notes span the platform's main domains, including AI and machine learning, Python and programming, web development, DevOps, cloud, security and databases. Coverage mirrors the 37 live courses, so notes exist for the topics you are actually studying, and new note sets are added as courses launch.
How are SkillVeris study notes different from regular textbooks?
The notes are answer-first, concise and free, whereas textbooks are long and often expensive. Each section explains one concept directly, then reinforces it through selectable hobby analogies like cricket or cooking. Notes also cross-link to the glossary, blog and cheat sheets, letting you jump to related material instantly instead of flipping pages.
Can I use the developer study material without creating an account?
The study notes are free to access, and SkillVeris does not charge anything for its developer study material at any point. Browsing notes is straightforward from the Study Notes section, and if you want progress tracking, certificates and AI Mentor conversations tied to your learning, a free account unlocks those extras.
Do the study notes explain concepts with analogies?
Yes, this is a signature SkillVeris feature. Study notes use the Learn Through Hobbies method, explaining technical concepts through analogies from twelve domains including cricket, music, gaming, photography, travel, movies, fitness, chess, cooking, finance, business and sports. You can switch the analogy domain instantly to whichever hobby makes the concept click.
Are the revision notes suitable for last-minute exam preparation?
Yes, revision notes on SkillVeris work well for last-minute preparation because every section states the answer in its first sentences, so skimming is genuinely effective. Pair them with the relevant cheat sheet for formulas and syntax, and use the glossary for any unfamiliar term you meet while cramming.
Is there free study material for AI and machine learning?
Yes, SkillVeris provides free study notes across its AI and ML catalogue, covering Python for AI, deep learning frameworks like PyTorch and TensorFlow, Hugging Face Transformers, Large Language Models, RAG, AI agents and MLOps. All of it is free, making it a strong resource for Indian students and global learners alike.
Can beginners understand the study notes, or are they for experts?
Beginners can absolutely use them. The notes are written in plain language, define terms as they appear, and lean on hobby analogies to make abstract ideas concrete. Difficulty scales with the underlying course level, so beginner-course notes stay gentle while advanced-course notes go deeper, and the glossary supports you throughout.
How do study notes connect with SkillVeris courses?
Study notes are organised by course and topic, so they map directly to the structured courses and their 24–40-lesson curriculum. Many learners study a lesson first, then use the matching notes for revision before module assessments and the final exam, where 80 percent is required to pass and earn the certificate.
Are there study notes for Python specifically?
Yes, Python is well covered through notes tied to the Python-focused courses, including Python for AI and ML. Topics span fundamentals through applied machine learning usage. You can reinforce the notes with Python practice in Code Lab, which runs code in your browser with no installation required.
Do the study notes include code examples?
Yes, study notes include code examples wherever a concept is best shown in code, alongside explanations, key points and analogies. Reading a snippet in the notes and then reproducing it yourself in Code Lab is an effective loop, since Code Lab lets you run code in the browser across six languages.
How often is new study material added to SkillVeris?
Study material grows alongside the course catalogue. Whenever new courses join the platform's 37 live courses, matching study notes, glossary entries and cheat sheets are added so the resources stay in sync. Existing notes are also refined over time, so it is worth revisiting topics you studied earlier.
Can I use SkillVeris notes to prepare for technical interviews?
Yes, the notes make excellent interview revision because they compress each concept into direct, answer-first explanations, which mirrors how you should answer interview questions. Combine them with the SkillVeris interview questions feature, which includes readiness scoring, to test whether your revision has actually made you interview-ready.
Are the study notes mobile-friendly for studying on the go?
Yes, the study notes are built to load fast and read comfortably on mobile devices, so you can revise during a commute or between classes. Sections are short and answer-first, which suits small screens, and analogy switching works on mobile too, letting you study anywhere without carrying books.
What is the difference between study notes and cheat sheets?
Study notes explain concepts in depth with context, examples and analogies, making them ideal for learning and revision. Cheat sheets are compact quick-reference summaries of syntax, commands and key facts, ideal once you already understand a topic. Most learners study the notes first, then keep the cheat sheet handy while coding.
Do study notes help if I am stuck on a course lesson?
Yes, reading the matching study notes often clarifies a lesson because the same concept is explained from a different angle, frequently with a different analogy. If you are still stuck, ask the AI Mentor, which answers 24/7 at Quick, Detailed or Deep-dive depth until the idea genuinely makes sense.
Is there free study material for DevOps and cloud topics?
Yes, SkillVeris carries free study notes for DevOps and cloud topics as part of its coverage across 37 live courses. The material suits learners following the DevOps Engineer or Cloud Engineer paths, and it links to related glossary terms and cheat sheets so you can revise the whole toolchain in one place.
Can school or college students in India use these notes for projects?
Yes, students across India and worldwide use SkillVeris notes for coursework, projects and exam preparation, and everything is free, which matters for student budgets. The notes explain concepts clearly enough to cite in project reports, and Code Lab lets you prototype the project code directly in your browser.
How should I combine study notes with other SkillVeris resources?
A proven loop: learn from a course lesson, revise with the matching study notes, look up unfamiliar terms in the glossary, keep the cheat sheet open while practising in Code Lab, and quiz yourself with interview questions. The AI Mentor fills any remaining gaps 24/7, at whatever depth you need.

What Learners Say

Real journeys from the SkillVeris community — swipe for more.

SkillVeris taught me Python through Cricket. Now I’m building real projects and feeling confident!
Arjun S. · B.Tech Student
The best platform for hobby-based learning. Concepts finally stick.
Priya R. · Data Analyst
I went from zero coding to a portfolio of projects — all by learning through my love for gaming. Landed my first internship!
Kabir M. · CS Undergraduate
Trending Topics50 popular tags — tap to explore
Trending CoursesAll 37 free courses — tap to browse