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
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:
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 where mockOpportunities is
then after have defined the mock for the class to test ( Fflib_ISObjectUnitOfWork ) and called the method to test
we can crack on with some verification:
We can verify that the method is called with a specific parameter:
or better, since times(1) is the default behavior with
It’s easy to guess the next verification;
In case you want to assert that a method has NOT been called you can use times(0), or more elegantly
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()
atLeastOnce()
atMost()
between()
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
would add a custom message in case the test fails.
All those methods can be combined together:
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:
- 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
- Matchers
- ApexMock blogs from Jesse Altman
- ApexMocks Capture Support
- Answering with Apex Mocks
- Verify call’s order in Apex unit tests
[…] Counters in Apex Mocks verifications […]
LikeLike
[…] Counters in Apex Mocks verifications […]
LikeLike