D'fflib
HOWLayers

Testing & Mocking

Elaborating on the benefits of mocking, and how to properly set up test data to mock methods with. Including thorough and extensive example code snippets.

Work in progress

This article is under construction and will be released shortly. The outline already shows the intended structure.

  • Until this article is finalised, our blog post "Extensive test/mocking example guide in fflib" already takes you along mocking, stubbing, verification and test data builders end to end.
  • D'fflib-specific shortcuts (e.g. selector assertion methods) are covered in the Selectors article.

Characteristics

Responsibilities

Considerations

  1. Test segregation: test single-responsibility vs. end-to-end tests in Apex Unit Tests; mocking everything, most or none (all data insertion)
  2. Test deduplication: avoid testing the same logic multiple times by reusing test data builders and mocking dependencies

Rules


Initiation

How to call

Test classes are never called from code. They're run through the Salesforce CLI, either as part of a release (by the deployment test level), separately, or by a manual run from the Developer Console or Setup.

sf apex run test --class-names CTRL_RoomReservationsTest

Class guideline

Below skeleton is a suggestion for how to structure test classes for ease of readability and maintenance. Reasoning is elaborated in the Guidelines section.

@IsTest( isParallel = true )
private with sharing class CTRL_RoomReservationsTest{
    @IsTest
    private static void methodName_scenario(){
        // Create mocks
        // Given - create data
        // Set mocks
        // When - perform test
        // Then - validate ...
    }
}

Standard methods

Each unit test follows the same three steps: construct the test data, mock the dependencies, and verify whether the single-responsibility was satisfied, by asserting return values and layer-interactions.

This article follows one scenario from start to end: the Room Booking controller CTRL_RoomReservations and its test class CTRL_RoomReservationsTest.

1. Test data

This section will show how to construct the test data for the scenario, using the Test Data Builder Framework.


2. Mock dependencies

This section will show how to replace each dependency of the class under test by a mock, and how to program its responses.

Stubbing vs mocking

The terms stubbing and mocking are often used interchangeably, but this isn't factually correct. Stubbing means faking a response, and mocking is verifying the interaction.

Stub classes

  • Expected behaviour for methods on a stubbed class

Override behaviour

  • Void vs. non-void methods
  • Link to Matchers section (to centralise for stubbing and mocking)

Inject mocks

  • How to pass into (D')fflib and the internal mechanics

defineMock()

  • Simplified way to create and register a mock in one step

3. Verification

  • Return variable
  • Layer interactions
  • Link to Matchers section (to centralise for stubbing and mocking)
  • ArgumentCaptor

Matchers

  • Guidance regarding either all matchers on none
  • Different Matcher methods (eq, sObjectWith)

Test Data Builder Framework

This section will cover how to define test data once and reuse it across all test classes.

Anatomy of a builder

This section will cover how to create a builder and register it in TestFactory.

Output modes

ModeMethodDB hit?Ids populated?Formula fields?When to use
Pure mock.mock()✗✗✓Unit tests where no Id is needed
Mock with IDs.mockWithIds()✗✓ (fake)✓Unit tests that read .Id or traverse lookups
Database insert.save()✓✓ (real)✗Integration tests requiring real records

Example JSON output

Advanced features

  • dfflib_UT_Utils with SaveResults, createSObjectList, Profile cache,
  • SObjectType defined defaults
  • Replacers for autonumbers, or random values

Layer specific tests

Each layer article covers how to test that layer in isolation:

Trigger coverage

Salesforce requires every trigger to have some test coverage before it can be deployed. In a codebase which fully adopted (D')fflib, Domain and handler tests mock all DML, so no SObject is inserted or updated and the triggers stay at 0% coverage, causing deployments to fail.

While we're defensive on adding code "just for the sake of code coverage", this is the one place where real DML is intended. An option for this is to:

  • Create one TriggersTest class, with one test method per SObject that has a trigger, like TriggersTest.
  • Each method performs a single real insert of a minimal record, which executes the trigger and its triggerHandler() call.
  • Don't assert business logic here: the handlers are already tested in isolation, see Testing a Trigger. Asserting it again tests the same logic twice and makes the test fragile to unrelated handler changes.
  • Add a method to this class whenever a new trigger is added.

Alternatively, an end-to-end test that already inserts the SObject covers its trigger as well.


Migration steps

No migration steps are required to realise a compilable D'fflib codebase. However, once D'fflib is installed (Getting Started), we suggest leveraging these functionalities to reduce unit test runtimes and make test methods more readable and maintainable.

  1. Selector unit tests
    After upgrading Selectors, avoid the query to be performed, saving precious time. Follow the "Test class changes" in the Selectors migration steps to replace data creation by strict query assertions.
  2. Layer mocks to defineMock() See before and after code in the feature article.
  3. Move inline test data to Builders
    1. When writing or touching a test class, identify inline SObject constructions (new Account( ... ), insert acc, repeated field assignments)
    2. Create a builder for that SObject and move scenario-specific field combinations into as*() methods
    3. Replace the inline constructions by TestFactory calls, keeping test-specific overrides on the builder call

Except for the listed items, the content on this site is licensed under CC-BY-NC-4.0
and allows sharing, provided an appropriate credit and link to source.

On this page