Reputation: 1993
I have a simple class with a parser
class Parser
{
public function __construct(P1 $p1, P2 $p2)
{
$this->p1 = $p1;
// etc...
}
public function parse()
{
$this->doSomething1();
return $this->doSomething2(P3 $p3);
}
}
then I have my test class
class ParserTest
{
public function testParse()
{
$p1 = $this->getMockBuilder(P1::class)->disableOriginalConstructor()->getMock();
$p2 = $this->getMockBuilder(P2::class)->disableOriginalConstructor()->getMock();
$p3 = $this->getMockBuilder(P3::class)->disableOriginalConstructor()->getMock();
$parser = new Parser ($p1, $p2);
$result = $parser->parse($p3);
}
}
what I need to do is disable doSomething1 for the test because it is basically doing an API call, so I can test what is in result. How can I do that?
Upvotes: 2
Views: 257
Reputation: 39420
You could use a PHPUnit partial mock (I didn't find a valid doc for this, only some PR or in the source code) of your class under test, as example:
$methods = ["doSomething1"];
$parser = $this->getMockBuilder(Parser::class)
->disableOriginalClone()
->disableArgumentCloning()
->disallowMockingUnknownTypes()
->onlyMethods($methods)
->setConstructorArgs([$p1, $p2])
->getMock();
NB: Because you need to pass data in the constructor you can't use the short-cat version:
$this->createPartialMock(Parser::class, $methods);
Upvotes: 0
Reputation: 1844
As El_Vanja already suggested, it's best to extract that API call. If you can't do it right now, you can override the doSomething1
method for the test:
class ParserTest
{
public function testParse()
{
$p1 = $this->getMockBuilder(P1::class)->disableOriginalConstructor()->getMock();
$p2 = $this->getMockBuilder(P2::class)->disableOriginalConstructor()->getMock();
$p3 = $this->getMockBuilder(P3::class)->disableOriginalConstructor()->getMock();
$parser = new class($p1, $p2) extends Parser {
protected function doSomething1()
{
}
};
$result = $parser->parse($p3);
}
}
Upvotes: 1