sebastianbergmann/phpunit — Issue #478: Code coverage discrepancy using getObjectForTrait
Author: rdlowrey
Created: 2012-02-01 18:25:07+00:00
State: open

When using `getObjectForTrait` PHPUnit reports a different code coverage % for the same test when run in isolation as compared to when the entire test suite is run. So, when I run only the specific test in question using `phpunit test/src/artax/UsesRequestTraitTest` I get the following coverage:

![isolation](http://i.imgur.com/xJILM.png)

However, if I run my full suite of tests using `phpunit` without specifying a specific test, I receive the following for the same file:

![full_suite](http://i.imgur.com/vnoFT.png)

Here's the source code for the test:

```php
getObjectForTrait('artax\UsesRequestTrait');
$this->assertAttributeEmpty('request', $traitObj);
return $traitObj;
}

/**
* @depends testIsInitiallyEmpty
* @covers artax\UsesRequestTrait::setRequest
* @covers artax\UsesRequestTrait::getRequest
*/
public function testSetterAssignsRequestProperty($traitObj)
{
$r = new artax\blocks\http\HttpRequest();
$traitObj->setRequest($r);
$this->assertEquals($r, $traitObj->getRequest());
}
}
```

And the actual graphical coverage report for the 60% coverage version. The lines shown as uncovered below are green (covered) when the test is run in isolation:

![coverage](http://i.imgur.com/ZQYw3.png)

---

However, the discrepancy disappears when using a concrete implementation class for testing the trait in place of the built-in `getObjectForTrait` method. So, the following changes to the above code resolve the issue:

```php
getObjectForTrait('artax\UsesRequestTrait');

// use a concrete implementation instead (see bottom for class definition)
$traitObj = new TraitImplementationClass();
$this->assertAttributeEmpty('request', $traitObj);
return $traitObj;
}

/**
* @depends testIsInitiallyEmpty
* @covers artax\UsesRequestTrait::setRequest
* @covers artax\UsesRequestTrait::getRequest
*/
public function testSetterAssignsRequestProperty($traitObj)
{
$r = new artax\blocks\http\HttpRequest();
$traitObj->setRequest($r);
$this->assertEquals($r, $traitObj->getRequest());
}
}

// using this class to test instead of getObjectForTrait resolves the issue
class TraitImplementationClass
{
use artax\UsesRequestTrait;
}
```

The environment used is **PHP_CodeCoverage 1.1.1** using **PHP 5.4.0RC6** and **PHPUnit 3.6.10**