Counters in Apex Mocks verifications

The very core of the Mocks verification checks whether a method has been called or not. Typically with Apex Mocks you can achieve that  with

Screen Shot 2017-04-01 at 11.34.30

Screen Shot 2017-04-01 at 11.35.49

Since the beginning, Apex Mocks aimed to have a syntax that looks like Mockito. Recently Apex Mocks have narrowed the gap with Mockito, getting new counters functionality with a syntax that it’s getting closer to the well know Java mocking library.

Those new functionalities are:

  • times(Integer times)
  • description(String customAssertMessage)
  • atLeast(Integer atLeastTimes)
  • atMost(Integer atMostTimes)
  • atLeastOnce()
  • between(Integer atLeastTimes, Integer atMostTimes)
  • never()

Let’s have a look at some examples on how they work.

The following examples are contained in this ApexMocksExamples project, that you can download and do your Apex Mock experiments. This project is based on the fflib-apex-common and  Enterprise Patterns.

This is the method that we are going to test:

Screen Shot 2017-04-01 at 11.55.58.png

That is not particularly pretty or efficient but helps me to show how to test the calls on the registerDirty() method.

First of all, we need to stub OpportunitiesSelector Screen Shot 2017-04-01 at 11.59.52where mockOpportunities isScreen Shot 2017-04-01 at 12.02.41 then after have defined the mock for the class to test ( Fflib_ISObjectUnitOfWork ) and called the method to test

Screen Shot 2017-04-01 at 12.04.17.png

we can crack on with some verification:

We can verify that the method is called with a specific parameter:

Screen Shot 2017-04-01 at 17.02.52or better, since times(1) is the default behavior with

Screen Shot 2017-04-01 at 17.02.38

It’s easy to guess the next verification;

Screen Shot 2017-04-01 at 17.12.51

In case you want to assert that a method has NOT been called you can use times(0), or more elegantly

Screen Shot 2017-04-01 at 17.11.54

The times() and never method perform a strict validation on the number of times of the method’s calls, but sometimes you need to enforce looser controls and in that case:

atLeast()

Screen Shot 2017-04-05 at 18.26.56

atLeastOnce()

Screen Shot 2017-04-05 at 18.27.42

atMost()

Screen Shot 2017-04-05 at 18.27.03

between()

Screen Shot 2017-04-05 at 18.27.12

would give you more flexibility on your verifications.

The last feature is not a counter, but would help to give more readability and would help to debug a failing test, the description() method

Screen Shot 2017-04-01 at 17.27.08

would add a custom message in case the test fails.

All those methods can be combined together:Screen Shot 2017-04-01 at 17.32.56

With those new features of Apex Mocks you can make your tests even more beautiful.

Happy Mock Testing.

 

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

 

Other Resources:

Advertisements