Skip to content

jasonsiders/apex-database-layer

Repository files navigation

apex-database-layer

Welcome to apex-database-layer, an open-source library used to easily mock Salesforce database operations in Apex.

Features

Apex Database Layer was designed to be feature-rich, yet easy to use, closely mirroring standard platform patterns.

You get the following out of the box:

Best of all, the framework is built 100% on the Salesforce platform, using standard Salesforce technology. It's open source, and free, and it always will be.

Installation

apex-database-layer is available for free as an unlocked package. You can find the latest or past versions in the Releases tab.

Use the following command to install the package in your environment:

sf package install --package {{package_version_id}} --wait 10

Usage

Once intalled, use DatabaseLayer.Dml for all of your DML operations:

// Don't use these standard apex DML methods:
insert account;
Database.insert(account);
// Use this instead:
DatabaseLayer.Dml.doInsert(account);

Use DatabaseLayer.Soql for all of your SOQL queries:

List<Account> accounts = (List<Account>) DatabaseLayer.Soql.newQuery(Account.SObjectType)
  ?.addSelect(Account.Name)
  ?.addWhere(Account.OwnerId, Soql.EQUALS, UserInfo.getUserId())
  ?.orderBy(Account.LastModifiedDate, Soql.SortDirection.DESCENDING)
  ?.setRowLimit(200)
  ?.toSoql()
  ?.query();

Once this is done, you can instantly decouple your Dml and Soql operations from the Salesforce database in apex tests, with just a single line of code:

DatabaseLayer.useMocks();

In apex tests, you can easily generate test records for use in mocks, that would otherwise require extensive database operations:

// This operation takes ~2ms; would require 4 separate DML operations otherwise:
OpportunityContactRole contactRole = (OpportunityContactRole) new MockRecord(OpportunityContactRole.SObjectType)
  ?.withId()
  ?.toSObject();

Want To Learn More?

Head over to our wiki, which includes articles about:

  • Mocking database operations, and why it's important
  • Techniques for mocking using the framework
  • Documentation for all public classes & methods

About

A slim, extensible DML & SOQL Mocking Library.

Resources

License

Stars

Watchers

Forks

Languages