P
P
Phoen1xx2019-03-06 16:17:01
PHP
Phoen1xx, 2019-03-06 16:17:01

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 );
      }
   }
}

How to test doSomething? The problem is that setData cannot be run in tests, but you need to find out what parameters were passed to it, because this is the result of doSomething

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexey Ukolov, 2019-03-06
@Phoen1xx

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);
    }
}

https://phpunit.de/manual/6.5/en/test-doubles.html

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question