Home Salesforce Testing using Dependency Injection and Mocking

Testing using Dependency Injection and Mocking

by Dhanik Lal Sahni

75% Test coverage for Salesforce application is very important. Without 75% code coverage we can not move code in production. This post will help in resolving test classes coverage issue for dependent classes.

Dependent classes create issue while test class coverage.  We should utilize mocking framework for completing test coverage.

Let us take example we have below class for AccountService which will notify when new account is created.  As notification can be different based on condition, notification object will be created dynamically.

We have two important piece of code to for test coverage

  1. INotification interface and its class test coverage
  2. BaseException class and exception test coverage

INotification Object Test Coverage

INotification interface will get object at runtime. To test this we have to create a mock object for this interface.  Mock object will return required string, which will help to continue flow in caller class like AccountService.

private class MockNotification implements INotification
{
  string returnString;
  MockNotification(string data)
  {
    returnString=data;
  }
  public string sendNotification()
  {
    return returnString;
  }
}

And it will be used like below code

AccountService service=new AccountService(new MockNotification('EMAIL'));
service.addAccount(act);

BaseException Class Test Covergae

Exception will be tested using try and catch block. We can catch exception and can check exception message with system.assertEquals. 

try
{
   AccountService service=new AccountService(new MockNotification('SMS'));
   service.addAccount(act);
}
catch(BaseException ex)
{
    system.assertEquals('Account can not be created for Email', ex.getMessage());
}

Complete Test class Code:

You may also like

Leave a Comment