ApexMocks is a mocking framework for the Force.com Apex language.
It derives it's inspiration from the well known Java mocking framework Mockito
![Deploy to Salesforce](https://raw.githubusercontent.com/afawcett/githubsfdeploy/master/src/main/webapp/resources/img/deploy.png)
ApexMocks allows you to write tests to both verify behaviour and stub dependencies.
An assumption is made that you are using some form of Dependency Injection - for example passing dependencies via a constructor:
public MyClass(ClassA.IClassA dependencyA, ClassB.IClassB dependencyB)
This allows you to pass mock implementations of dependencies A and B when you want to unit test MyClass.
Lets assume we've written our own list interface MyList.IList that we want to either verify or stub:
public class fflib_MyList implements IList
{
public interface IList
{
void add(String value);
String get(Integer index);
void clear();
Boolean isEmpty();
}
}
// Given
fflib_ApexMocks mocks = new fflib_ApexMocks();
fflib_MyList.IList mockList = new MockMyList(mocks);
// When
mockList.add('bob');
// Then
((fflib_MyList.IList) mocks.verify(mockList)).add('bob');
((fflib_MyList.IList) mocks.verify(mockList, fflib_ApexMocks.NEVER)).clear();
fflib_ApexMocks mocks = new fflib_ApexMocks();
fflib_MyList.IList mockList = new MockMyList(mocks);
mocks.startStubbing();
mocks.when(mockList.get(0)).thenReturn('bob');
mocks.when(mockList.get(1)).thenReturn('fred');
mocks.stopStubbing();
Run the apex mocks generator from the command line.
java -jar apex-mocks-generator-4.0.0.jar
<Filepath to source files>
<Filepath to interface properties file>
<Name of generated mocks class>
<Filepath to target files - can be the same as filepath to source files>
<API version of generated mocks class - optional argument, 30.0 by default>
//E.g. the command used to generate the current version of fflib_Mocks.
java -jar apex-mocks-generator-4.0.0.jar "/Users/jbloggs/Dev/fflib-apex-mocks/src/classes" "/Users/jbloggs/Dev/fflib-apex-mocks/interfacemocks.properties" "fflib_Mocks" "/Users/jbloggs/Dev/fflib-apex-mocks/src/classes" "30.0"
Full documentation for ApexMocks can be found at Code4Clode:
- 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
Documentation from Jesse Altman