class A{
protected $data;
public function setData($data){
$this->data = $data;
file_put_contents('a.txt', $data);
}
}
class B{
public function doSomething(A $a, $x){
if( $x > 10 ){
$a->setData( $x * $x );
}else{
$a->setData( $x * 20 );
}
}
}
class MyTest extends \PHPUnit\Framework\TestCase
{
public function testDoSomethingOne(): void
{
/** @var \PHPUnit\Framework\MockObject\MockObject $mockOfA */
$mockOfA = $this->getMockBuilder(A::class)->getMock();
$mockOfA->expects($this->once())
->method('setData')
->with(20);
(new B)->doSomething($mockOfA, 1);
}
public function testDoSomethingTwo(): void
{
/** @var \PHPUnit\Framework\MockObject\MockObject $mockOfA */
$mockOfA = $this->getMockBuilder(A::class)->getMock();
$mockOfA->expects($this->once())
->method('setData')
->with(10000);
(new B)->doSomething($mockOfA, 100);
}
}
The practice of replacing an object with a test double that verifies expectations, for instance asserting that a method has been called, is referred to as mocking.