public class MyController {
  private MyService myService;
  public MyController(MyService myService) {
    this.myService = myService;
  public Integer calculateTotalValue(Integer valueOne, Integer valueTwo) {
    return myService.calculateValues(valueOne, valueTwo);

The basic idea behind mocking is that given a set of parameters, return a 
pre-defined result.

Different ways to implement mocks:

1. Dependency Injection
2. Using Interface
3. Using custom settings with Type.forName()
4. Replace the method with a new implementation that returns the mocked result

public class MyControllerTest {
  public static testMethod void testCalculateValues() {
    fflib_ApexMocks mocks = new fflib_ApexMocks();
    MyInterface mockMyService = new MockMyService(mocks);


    MyController controller = new MyController(mockMyService);
    Integer totalValue = controller.calculateTotalValue(5, 3);

    System.assertEquals(8, totalValue, 'The service should return 8');

mocks.verify(mockMyService)).calculate(5,3); // verify this method was called.

When we mock a method, it means that we do not want to run that method.

// Actual code, but we need to mock out the email sending part because
// email sending is typically slow, or we may not want to send test emails
public bool AddCustomer(MyEmail obj) {
  // some ADO.NET code
  return true;

The step to mock something might involve:

1. Create the object
2. Specify which function you want to by pass.

Mock<MyEmail> objEmail = new Mock<MyEmail>();
objEmail.setup(x => x.SendEmail()).returns(true);

Customer obj = new Customer();

In the above code, the AddCustomer method takes an object of the MyEmail
class, which implements the SendEmail method.  In the test code, we invoke
the AddCustomer method, passing it a mocked object which has the SendEmail
method but it was mocked to return true.
Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License