apex-enterprise-patterns / fflib-apex-mocks

An Apex mocking framework for true unit testing in Salesforce, with Stub API support
BSD 3-Clause "New" or "Revised" License
423 stars 214 forks source link

There is no way to mock void methods #126

Closed AllanOricil closed 1 year ago

AllanOricil commented 3 years ago

I have service classes which are used on OnBefore events that don't return anything. They literally just pass info to a Domain,which also does not return anything, to update my record data. I wanted to mock this service method and I couldn't because it is always expecting a "thenReturn()". I would like to mock this method because I want to use verify to check it has been called.

stohn777 commented 3 years ago

@AllanOricil Skip specifying the mocks.when(...) statement. Simply do the verify. As in ...

fflib_ApexMocks mocks = new fflib_ApexMocks();
IMyService mockMyService = (IMyService) mocks.mock(IMyService.class);

// Execute the test implementing the void method

((IMyService) mocks.verify(mockMyService, 1))
    .doSomethingUseful(
        fflib_Match.sObjectWith(
            new Map<SObjectField, Object> {
                Contact.Id =>expectedId,
                Contact.Nickname__c => expectedNickname,
                Contact.LastSynchronized__c => expectedSyncedOn
}));

The "Matching" logic is optional but illustrates if needed.

AllanOricil commented 3 years ago

@stohn777 cool. I will try that :D