When I first started working on ApexMocks, the easiest path to take was to use strings when stubbing and verifying. For example:
Here we are stubbing the ‘get’ method of the MyList class to return our stubbed value. Notice that we are specifying the method to stub via a string parameter to the call to the mock framework when() method.
mocks.verify(ApexMocks.NEVER, myList, 'add');
Here we are verifying that the add method of the MyList class was never called. Again notice that we have specified the method to verify as a String – ‘add’.
Whilst this was the easiest path to take, it’s less than ideal for a number of reasons:
- it’s error prone – I can easily make a typo in the method argument ‘adf’ instead of ‘add’ for example
- as an API it’s a bit on the ugly side, the test code is not as elegant and readable as it could be
- it makes solving the problem of stubbing and verifying method arguments more difficult
- we’re not making best use of the Apex compiler – if we could call the real methods, we get all the benefits of our test code being compiled properly!
So next time we will start to use the latest version of the ApexMocks framework which allows us to use real method calls when stubbing and verifying behaviour.
We’ll see how to define the component interface we want to stub or verify, how to auto-generate and inject a mock implementation of our interface into our unit test class, and finally how to write ApexMocks unit tests.
And yes – I’ll make the mock framework itself available via our FinancialForce.com GitHub repository 🙂