When to use unit testing mock objects ?
Usually when to write unit test, you are trying to test if a small piece of code is working as intended. But there are some times when part of that small code depends upon third party web service or database connection that are simply out of your control.Thats when you use mock objects which would behave exactly as you tell them.
Following is simple code example that would explain it further:
class DataManager {
private $exception_logger;
public function __construct(IExceptionLogger exception_logger){
$this->exception_logger = $exception_logger;
}
public function find_user_by_email($email){
try{
$user_data_store = new UserDataStore();
$user = $user_data_store->find_by_email($email);
return $user;
}catch(Exception $ex){
$this->exception_logger->log($ex);
}
}
}
To test above code you could write unit test that would fetch user record based on email address. But how would you unit test if user data store object throws exception?
In that case change your code as following :
class DataManager
{
private $user_data_store;
private $exception_logger;
public function __construct(IUserDataStore $user_data_store,IExceptionLogger exception_logger){
$this->user_data_store = $user_data_store;
$this->exception_logger = $exception_logger;
}
public function find_user_by_email($email){
try{
$user = $this->user_data_store->find_by_email($email);
return $user;
}catch(Exception $ex) {
$this->exception_logger->log($ex);
}
}
}
Now in your unit test. Pass “Mocked” user data store class which would behave exactly as you specify. In this case it would throw an exception when call is made to its find_by_email() method.
This way you can write unit test if your exception logger class gets called and exception is recorded by logging class which wouldn’t have been possible in previous case.
I hope this clears concept of mocking in unit testing