(help) TDD. Phpunit + DI

Assuming I had something like:

class TestedClass{
public function foo( $value ){
return 'Tested ’ . $value;
}
}

class ToTest{
public function __construct(TestedClass $class)
{
$this->class = $class;
}

public function Baz($value){
    return $this->class->foo($value);
}

}

TestedClass has already been tested. I know that ‘Tested’ is correctly been assigned and returning fine.

Would/Should I be writting unit tests for ToTest() to check that TestedClass::foo() is being called correctly as well?

If so how would you mock up the depancy so you can check that the value is correct I tried:

$TestedClass = $this->getMockBuilder('\TestedClass')
    ->disableOriginalConstructor()
    ->getMock();

$TestedClass->expects($this->once())
    ->method('foo')
    ->will($this->returnValue('return'));

// pass the mock into tested object
$Test = new \ToTest($TestedClass);

// run test
$this->assertEquals($Test->debug('rnd'), 'Testedrnd');

What I want to be able to test is

a) The TestClass::Foo is called when calling ToTest::Baz
b) The value of that based on the parameter set in ToTest::Baz

Any pointers would be much appreciated.

Add your test to the mocked method. Something like:

$TestedClass->expects($this->once())
  ->method('foo')
  ->with($this->equalTo($expected))
  ->will($this->returnValue('return'))

The with clause will have the value being passed to foo. And of course you set $expected to whatever you expect the value to be.

Been awhile since I used mockBuilder so I hope I got the syntax right. phpunit has support for a different mock framework call Prophecy which I find to be a bit clearer.

1 Like

being the key part, little more reading into the docs and it becomes apparent how to use it. Thank you.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.