Search
Close this search box.

HOW TO WRITE TEST COVERAGE IN SALESFORCE Part 2

Red Argyle Logo without name
Red Argyle logo

Salesforce Test CoverageIn my last post How to Write Test Coverage in Salesforce, I went over the basics of Salesforce test coverage. Since then we have been working to get all of our code bases well above the 75% code coverage minimum. The most important part of test coverage, keeping your test data isolated, is always a growing challenge. New fields, new requirements, removed fields, all can require modifications in test coverage. When your a small agile team, having to modify code when your trying to just update the data model is a pain, even when its isolated, time is precious. Wouldn’t it be nice if your test data just wrote itself based on your metadata? Wait thats a great idea! And we already did it for you! Now let me show you how it works.

TestRecordFactory is a test data generator from Red Argyle, written by our Founder Tom Patros, that reads the metadata of your org and creates the records, fields, and lookup records you need for your tests. If your data model changes, your still good. But enough background, lets see what this can do.

First we define our test record

public with sharing class TestAccount implements ITestRecord {
  public sObject getDefaultRecord() {
    return new Account(Name = 'Example');
  }
  public Schema.SObjectType getSObjectType() {
    return Account.SObjectType;
  }
}

Next we use our data in a test

@isTest
private static void testAccountStuff() {
  Account account = (Account)TestRecordFactory.createRecord(new TestRecords.TestAccount());
  insert account;
  system.assert('Example', account.Name);
  system.assert('5555551212', account.Phone);
}

See simple test data creation. But wait, we didn’t set the Accounts’s Phone field did we? Don’t worry, we do it for you, we will populate all of the fields with simple data, or you can specify to only include required fields. That way, no matter what changes, or what admin goes in and just starts creating required fields, or removing some others, your data still comes out the way you need it.

Or perhaps you need to create multiple records. Or what if there is a required lookup?

private static void testAccountStuff2() {
  List accounts = (Account)TestRecordFactory.createRecords(new TestRecords.TestAccount(), 5);

  ChildObject__c child = (ChildObject__c)TestRecordFactory.createRecord(new TestRecords.TestChildObject(), 5);
  system.assertNotEquals(null, [select Id from ParentObject__c where Id = child.ParentObject__c]);
}

We cannot write your test coverage for you, but we hope this helps. Here at Red Argyle we have started to use this in projects and it helps a lot in terms of rapidly creating data for tests and keeping things up to date with rapidly evolving data models. So if you think this is cool, then go check it out on our GitHub.

Red Argyle logo
Red Argyle logo

Related Blog Posts