Cleaner inner class test fixture pattern

I favor this inner class test fixture pattern for Apex unit tests where a set of related objects are required. It leverages Apex’s support for named parameters when concrete SObject types are created making the code self describing and quick to modify including when fields are added. (Patterns like builder typically need extra methods adding when new fields are added.) And rather late in the day I’ve noticed that the result of an assignment is the value assigned (as in languages like Java).

These two language features together allow this high signal-to-noise ratio fixture style where a single line initializes, assigns and inserts each object:

@isTest
private class OneTwoThreeTest {
    class Fixture {
        One__c one;
        Two__c two;
        Three__c three;
        Fixture() {
            insert one = new One__c(Number__c = 12.34);
            insert two = new Two__c(One__c = one.Id, String__c = 'Hello');
            insert three = new Three__c(Two__c = two.Id, Checkbox__c = true);
        }
    }
    @isTest
    static void test() {
        Fixture f = new Fixture();
        // ...
    }
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s