Answering with Apex Mocks

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:

Screen Shot 2017-03-28 at 21.42.23

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:

Screen Shot 2017-03-28 at 22.04.11

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:

Screen Shot 2017-03-30 at 21.07.02.png

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:

Screen Shot 2017-03-30 at 21.13.25

we can then use the arguments of the invocation of the stubbed method to define our Answer, for example:

Screen Shot 2017-03-30 at 21.25.52

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:

Screen Shot 2017-03-30 at 21.43.56

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:

Screen Shot 2017-03-30 at 21.48.21.png

breaking down the method we have the stubbing

Screen Shot 2017-03-30 at 21.58.29

where mockLines is

Screen Shot 2017-03-31 at 21.49.29

and since the answer triplicates the lines the expected lines to be registered in the unit of work would be

Screen Shot 2017-03-31 at 21.54.56.png

The Answer is a new powerful tool in your Apex Mocks tool box that would help where the classic stubbing is not enough.

Happy mocking.

The code of those examples can be downloaded from my GitHub repo.

Other Resources:

3 thoughts on “Answering with Apex Mocks

Leave a comment