From functional tests to unit tests
2012-10-17Sometimes I run into tests that look like unit tests, but are really functional, integration, or smoke tests instead. An example of what that might look like is below. I'm using pseudocode to avoid messing with auth and such:
class TwitterService
{
public function getUser($screenName)
{
$response = file_get_contents('https://api.twitter.com/1.1/users/show.json?screen_name=' . $screenName);
return json_decode($response);
}
}
Then the test case would be something like this:
class TwitterServiceTest extends PHPUnit_Framework_TestCase
{
$protected $object;
public function setUp()
{
$this->object = new TwitterService();
}
public function testTwitterUserShowReturnsName()
{
$user = $this->object->getUser('rsarver');
$this->assertAttributeExists('name', $user);
$this->assertAttributeEquals('Ryan Sarver', 'name', $user);
}
}
So at first glance this may seem like a reasonable test, but this is not a true unit test because it relies on an external service. What would happen if the Twitter API was down? Your test would fail, through no fault of your own code. I ran into this a few months back with a test that was calling a service internal to our network that happened to be down for maintenance. In addition, this type of test adds extra latency to your test run because you have to wait for an HTTP call to return. If your tests are slow, people won't run them.