I need to extend a third party class I cannot modify. The class's dependencies are for the most part injected through the constructor, making them easy to mock. However the class also uses methods from a trait that call global services directly, destroying test isolation. Here's a code sample that illustrates the problem:
trait SomeTrait {
public function irrelevantTraitMethod() {
throw new \Exception('Some undesirable behavior.');
}
}
class SomeSystemUnderTest {
use SomeTrait;
public function methodToTest($input) {
$this->irrelevantTraitMethod();
return $input;
}
}
class MockWithTraitTest extends \PHPUnit_Framework_TestCase {
public function testMethodToTest() {
$sut = new SomeSystemUnderTest();
$this->assertSame(123, $sut->methodToTest(123)); // Unexpected exception!
}
}
How does one deal with a situation like this in PHPUnit? Can traits be mocked and injected somehow? The only solution I've found is to mock the SUT itself and just nullify the troublesome methods from the trait, leaving the actual SUT methods intact. But that doesn't feel right.