Sometimes stub a method to return a canned value is not enough.
Sometimes the method you are mocking has some side effect.
Sometimes you need to stub your method with a custom answer.
With Apex Mocks you can bring your stubbing to another level and cover those more complex scenarios, let’s see how.
Let’s say that you are testing n API that calls a method that has a side effect, like this one:
In our example, the method takes two lists of SObjects and copies the elements in those lists, actually doubling the size of the lists, but it returns only the contacts list.
In our test, to take control of what the doStuff() method return we can stub with a “classic” thenReturn(), or if we need a more complex stubbing use the following:
what is thenAnswer(new MyAnswer()) doing?
Setting the stubbed value to use a custom Answer.
Unlikely Mockito in Apex we cannot define the answer directly in the stubbing, but we have to define separately the answer and pass an instance to the method.
We can define and shape the answer as we need by implementing the fflib_Answer interface and the related answer() method:
ApexMock would then invoke the callback method “answer()” performing the operations that you have defined.
The fflib_InvocationOnMock instance in the parameter of the answer method gives us access to some handy data about the invocation that we are stubbing, in particular:
we can then use the arguments of the invocation of the stubbed method to define our Answer, for example:
We decided to take the List of OpportunityLineItem and copy for three times, instead of two of the real implementation.
but, first let’s have a look at the method we want to test:
Let’s concentrate for a second on the List<OpportunityLineItem> oppLines returned by the selector, that is then passed to the service, and saved in the DB through the unit of work.
As we said previously the doStuff method have a side effect on the Opportunity lines, now we have to test that the registerDirty is called with the expected lines:
breaking down the method we have the stubbing
where mockLines is
and since the answer triplicates the lines the expected lines to be registered in the unit of work would be
The Answer is a new powerful tool in your Apex Mocks tool box that would help where the classic stubbing is not enough.
The code of those examples can be downloaded from my GitHub repo.
- ApexMocks Framework Tutorial
- Simple Dependency Injection
- ApexMocks Generator
- Behaviour Verification
- Stubbing Dependencies
- Supported Features
- New Improved apex-mocks-generator
- ApexMocks Improvements – exception stubbing, base classes and more
- ApexMock blogs from Jesse Altman
- ApexMocks Capture Support
- Verify call’s order in Apex unit tests
- Counters in Apex Mocks verifications