Introducing ApexMocks Framework

The goals I set myself in creating a mocking framework for the platform are:

  • minimal impact on production code
  • ease of use
  • mockito style syntax

Mockito is a well known mocking framework for Java development. Personally I love the syntax it provides, it allows for the creation of very readable unit tests.

Any impact on production code should be absolutely minimal, ideally zero. We don’t want to litter production code with instrumentation code, nor do we want to have to write our production code in a way we wouldn’t have done just to use a mocking framework.

Keep in mind mocking makes the assumption we will be using dependency injection, so we also need a simple, light-weight approach for DI too.

So given all of that, the kinds of basic requirements I would envisage for a mocking framework are:

(1) basic when style stubbing

when(myClass, 'someMethod').thenReturn(someValue)

(2) specific argument matching

when(myClass, 'someMethodTakingStringArgument', 'argumentValue').thenReturn(someValue)
when(myClass, 'someMethodTakingIntegerArgument', 1).thenReturn(someValue)

(3) verify style behaviour verification

verify(myClass, 'someMethod’)
verify(myClass, 'someMethod', argumentValues)

(4) exception stubbing

when(myClass, 'someMethod').thenThrow(new MyException())

(5) argument matchers

when(myClass, 'someMethod', anyInteger()).thenReturn(someValue)

8 thoughts on “Introducing ApexMocks Framework

    • Apologies it has taken a little longer to make the framework available, I’m going to share a tutorial series first (starting next week) about how to use the framework.

      • I’m eager to see your solution, as I have been working on something similar and just recently (last night) found your blog. The timing is incredible!

  1. I’ve continued working on a similar mocking framework that is use-syntax based on the Moq library for .NET:
    You appear to have a lot of experience using DI and mocking in Apex, so I’d love to get your thoughts on ways to improve the tool.

  2. Pingback: One Batch Apex to rule them all (Part II) – versiononefirst__c

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s