fflib-apex-mocks

repository·master·Indexed 19 days ago

https://github.com/apex-enterprise-patterns/fflib-apex-mocks

A mocking framework for Salesforce Lightning Apex inspired by Mockito. It utilizes the Salesforce Stub API to create mock objects, stub dependencies using when(), and verify method call behavior with verify(). Includes fflib_ApexMocksUtils for setting read-only fields on SObjects.

Tokens
791
Snippets
4
Records
4
Agent score
16%

What's inside fflib-apex-mocks

  1. Stub dependencies with when()

    master

    Use when() to define canned responses for method calls on a mock object. To prevent side effects or unexpected behavior during the setup phase, you must wrap your stubbing logic between startStubbing() and stopStubbing().

    fflib_ApexMocks mocks = new fflib_ApexMocks();
    fflib_MyList.IList mockList = (fflib_MyList.IList)mocks.mock(fflib_MyList.class);
    
    mocks.startStubbing();
    mocks.when(mockList.get(0)).thenReturn('bob');
    mocks.when(mockList.get(1)).thenReturn('fred');
    mocks.stopStubbing();
  2. Verify behavior with verify()

    master

    Use the verify() method to ensure that specific methods on a mock object were called with the expected arguments and frequency. If the invocation does not match the expectation, an exception is thrown containing details about the expected vs. actual counts and arguments.

    You can also use fflib_ApexMocks.NEVER to verify that a method was specifically NOT called.

    // Given
    fflib_ApexMocks mocks = new fflib_ApexMocks();
    fflib_MyList.IList mockList = (fflib_MyList.IList)mocks.mock(fflib_MyList.class);
    
    // When
    mockList.add('bob');
    
    // Then
    ((fflib_MyList.IList) mocks.verify(mockList)).add('bob');
    ((fflib_MyList.IList) mocks.verify(mockList, fflib_ApexMocks.NEVER)).clear();
  3. Set read-only fields using fflib_ApexMocksUtils

    master

    Since formula fields and other read-only fields cannot be set directly on SObjects, use fflib_ApexMocksUtils.setReadOnlyFields to inject values into them for testing purposes. This method returns a new instance of the SObject with the specified fields populated.

    Account acc = new Account();
    Integer mockFormulaResult = 10;
    acc = (Account)fflib_ApexMocksUtils.setReadOnlyFields(
    		acc,
    		Account.class,
    		new Map<SObjectField, Object> {Account.Your_Formula_Field__c => mockFormulaResult}
    );
    System.assertEquals(mockFormulaResult, acc.Your_Formula_Field__c);
  4. Create mock objects with fflib_ApexMocks

    master

    ApexMocks leverages the Salesforce Stub API to dynamically generate mock implementations of classes or interfaces at runtime. Use the mock() method on an instance of fflib_ApexMocks to create these objects.

    fflib_ApexMocks mocks = new fflib_ApexMocks();
    fflib_MyList mockList = (fflib_MyList)mocks.mock(fflib_MyList.class);