At work we've been going through the fairly painful process of adding unit tests to existing code. I'd like to share one technique I've found useful, a way of testing methods that at first glance look like they have too many dependencies to easily get under test.
I'll be giving these examples in PHPUnit but any xUnit framework should be able to do something similar.
Consider a method like the following, which is the sort of thing you might have trouble seeing how to test:
class MyClass
{
public function getDataAndPublishRemotely()
{
$data = DataStore::getUnpublishedData();
$service = new SoapClient($SOME_WSDL);
$service->publish(preg_replace('/[^0-9a0z]+/', '', $data));
}
}
So this is doing some sort of DB call, then calling a SOAP service and publishing a cleaned-up version of the result. What makes this hard to test is the fact it's got two solid dependencies - a static call to some sort of DataStore layer and a direct instance of a SoapClient class.
Eventually the way to fix this sort of thing is to inject both of those dependencies separately, but that's too big a refactoring to tackle straight away. When you're modifying a class to get it under test you want to do small, easy-to-understand changes and get it under test ASAP.
One approach to getting it tested is to split the functionality that you think you can test into a separate method, like so: