Answer the question
In order to leave comments, you need to log in
How to test a method that calls methods of another class?
Hello. I have a class with a method that calls the setter of a third party object, it looks something like this:
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 );
}
}
}
Answer the question
In order to leave comments, you need to log in
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);
}
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question