Troubleshooting ApexMocks Issues

Troubleshooting ApexMocks Issues

On July 5, 2025, Posted by , In Apex,Salesforce Technical Questions, With Comments Off on Troubleshooting ApexMocks Issues
Troubleshooting ApexMocks Issues

Question

Why Am I Getting Unexpected Results While Using ApexMocks?

When using ApexMocks for unit testing in Salesforce, unexpected results can arise due to various reasons. Troubleshooting ApexMocks issues is essential to ensure accurate test outcomes. Some common symptoms include:

  1. Null pointer exceptions occur in the service class when mocking a selector, but no such exceptions appear when querying DML’d SObjects.
  2. Verification errors, such as:
    FATAL_ERROR|fflib_ApexMocks.ApexMocksException: Expected : 1, Actual: 0 -- Wanted but not invoked: fflib_SObjectUnitOfWork__sfdc_ApexStub.registerNew(SObject).
  3. Debug logs showing that a SOQL query is executed for a selector that should have been mocked and stubbed.
  4. Mocked services throwing exceptions that the test code under examination does not seem to receive.
  5. Code that worked previously with ApexMocks fails when rerunning test methods.
  6. Stubbing appears ineffective, as if the framework does not recognize it.

These issues typically stem from improper setup, argument mismatches, or incorrect stubbing techniques. Understanding the root cause and implementing best practices can help resolve these problems.

Answer

Common Reasons ApexMocks May Fail

Forgetting to Inject Mock Objects

One of the most common errors is neglecting to inject the mock objects (e.g., service, selector, domain, or unit of work). Injection must occur after setting up the mock. For example:

Application.Service.setMock(ISomeService.class, mockService);  
Application.Selector.setMock(mockSelector);  
Application.Domain.setMock(mockDomain);  
Application.UnitOfWork.setMock(mockUow);

Without proper injection, your code won’t recognize the mocks, and the tests will fail. Always ensure injection happens after stubbing.

CRS Info Solutions offers expert Salesforce online training with real-time projects and certification support. Their practical methods make you job-ready…!

Passing Incorrect Arguments to Mocked Methods

If the arguments passed during testing differ from those specified in the stubbed methods, the mock will not behave as expected. Consider this example:

AccountsSelector mockSelector = (AccountsSelector) mocks.mock(AccountsSelector.class);

mocks.startStubbing();
mocks.when(mockSelector.selectById(someIdSet)).thenReturn(someMockAccounts);
mocks.stopStubbing();

Application.Selector.setMock(mockSelector);

new MyClass().doStuff();  // Code under test

Here, if MyClass passes a different set of IDs to selectById(), the mock won’t return the expected result. Ensure arguments in stubbing match those in the actual call.

Forgetting to Stub SObjectType() for Selectors and Domains

When mocking selectors or domains, you must stub the SObjectType() method because the framework uses it to identify the SObject being handled. Here’s an example:

AccountsSelector mockSelector = (AccountsSelector) mocks.mock(AccountsSelector.class);

mocks.startStubbing();
mocks.when(mockSelector.SObjectType()).thenReturn(Account.SObjectType);
mocks.when(mockSelector.selectById(someIdSet)).thenReturn(someMockAccounts);
mocks.stopStubbing();

Application.Selector.setMock(mockSelector);

If you skip stubbing SObjectType(), your test will fail with null pointer exceptions or unpredictable results.

Forgetting to Close Stubbing with stopStubbing()

You must always close stubbing with mocks.stopStubbing(). Failure to do so can lead to errors or unexpected behavior. For example:

AccountsSelector mockSelector = (AccountsSelector) mocks.mock(AccountsSelector.class);

mocks.startStubbing();
mocks.when(mockSelector.SObjectType()).thenReturn(Account.SObjectType);
mocks.when(mockSelector.selectById(someIdSet)).thenReturn(someMockAccounts);
mocks.stopStubbing(); // Closing stubbing correctly

Skipping stopStubbing() can result in incomplete mock setups and cause unpredictable results.

Handling Null Pointer Exceptions in mocks.when().thenReturn()

If you see null pointer exceptions while stubbing, ensure you enclose the mocks.when(...).thenReturn(...) logic within startStubbing() and stopStubbing(). For example:

AccountsService mockService = (AccountsService) mocks.mock(AccountsService.class);

mocks.startStubbing();
mocks.when(mockService.execute('test')).thenReturn('result');
mocks.stopStubbing();

Application.Service.setMock(mockService);

Without the stubbing scope, the mocks.when() line won’t work as expected.

Using Custom Apex Types as Arguments

ApexMocks cannot automatically compare custom Apex types. For example:

AccountsServiceImpl mockService = (AccountsServiceImpl) mocks.mock(AccountsServiceImpl.class);

mocks.startStubbing();
mocks.when(mockService.execute(customType)).thenReturn(result);
mocks.stopStubbing();

To fix this:

  • Implement the equals() and hashCode() methods for the custom Apex type.
  • Use matchers such as fflib_Match.anyObject() if exact matching isn’t required:
mocks.when(mockService.execute((CustomType) fflib_Match.anyObject())).thenReturn(result);

Modifying Arguments After Passing Them to Mocked Methods

ApexMocks captures arguments by reference, so modifying them after passing can cause verification to fail. For example:

mockService.doStuff(argumentList);
argumentList.clear();  // Modifying after passing to mock

In this case, the verification will fail because the recorded argument is now empty. Avoid modifying arguments after passing them to mocked methods.

Verifying ApexMocks

When using mocks.verify, ensure all dependencies are properly initialized and mock objects are injected. For example:

((MyService)mocks.verify(mockService, mocks.times(1).description('Verify service method')))
    .execute(expectedArg);

If mockService is null or incorrectly set up, verification will fail.

Final Thoughts

By carefully following these troubleshooting steps, you can effectively resolve issues with ApexMocks and achieve reliable unit testing in Salesforce. Always validate your stubbing, ensure arguments match, and properly inject mocks to avoid common pitfalls.

Advance Your Career with Salesforce Online Training

Our Salesforce online training offers a hands-on learning experience to master essential skills for success in the CRM industry. The course covers key topics such as Salesforce Admin, Developer, and AI, blending theoretical concepts with practical, real-world projects. With live assignments and guidance from experienced instructors, you’ll gain the expertise to solve complex business challenges using Salesforce.

In addition to technical training, the program includes personalized mentorship, certification exam preparation, and interview coaching to help you excel in the job market. You’ll benefit from comprehensive study resources, practical exposure, and ongoing support. Upon completion, you’ll be job-ready with the skills and confidence employers seek.

Start your Salesforce journey today and unlock new opportunities! Join our FREE demo class now..!

Comments are closed.