Salesforce Apex Testing Basic Test Class


Example

This test class will test the IsBlank(...) method of SomeClass. Below is the example SomeClass. This class has only the one, basic static method, but you will be unable to deploy it to a production instance for use until you have reached the code coverage threshold.

public class SomeClass {

    public static Boolean IsBlank(String someData) {
        if (someData == null) {
            return true;
        } else if (someData == '') {
            return true; 
        } else {
            return false;
        }
    }

}

As one can see, this method is simply a if statement with three branches. To write an effective test class, we must cover each branch with code, and use System.assertEquals(...) statements to verify that the proper data was received from IsBlank(...).

@isTest 
public class SomeClass_test {

    @isTest 
    public static void SomeClass_IsBlank_test() {

        String testData;

        // SomeClass.IsBlank() returns true for Null values
        System.assertEquals(true, SomeClass.IsBlank(testData)); 

        testData = '';
        
        // SomeClass.IsBlank() returns true for empty strings
        System.assertEquals(true, SomeClass.IsBlank(testData)); 

        testData = 'someData';

        // SomeClass.IsBlank() returns false when testData is neither
        // an empty string nor Null
        System.assertEquals(false, SomeClass.IsBlank(testData)); 

    }

}