Mocking

https://developer.salesforce.com/page/Apex_Enterprise_Patterns_-_Separation_of_Concerns
http://jessealtman.com/2014/03/dependency-injection-in-apex
http://github.com/financialforcedev/fflib-apex-mocks

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

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

    mocks.startStubbing();
    mocks.when(mockMyService.calculate(5,3)).thenReturn(8);
    mocks.stopStubbing();

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

    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) {
  obj.SendEmail();
  // 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();
obj.AddCustomer(objEmail.Object);

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