I want to test the output of method checkCredentials()
:
Class BuildParticipant
{
public function __construct(DBConnectionWrapper $db, ?Logger $logger=null)
{
$this->participant = new ParticipantView($db);
// snip
}
public function build($participantId)
{
$credentialsOK = $this->checkCredentials($participantId, $this->participant);
// snip
}
protected function checkCredentials($participantId, Crud $participant): bool
{
$data = $participant->find($participantId)->nextRecord();
// do some logic on $data and return boolean
My original way of writing the function was not very testable:
protected function checkCredentials($participantId): bool
{
$data = $this->participant->find($participantId)->nextRecord();
I figured that injecting ParticipantView
into the method would allow me to inject a mock ParticipantView::find()
I’m having trouble crafting the mock (or stub – not sure about terminology)
<?php
use PHPUnitFrameworkTestCase;
class buildNewParticipantTest extends TestCase {
public function testCredentialInclusion()
{
$mockDb = $this->getMockBuilder('Database')->getMock();
// unsuccessful attempt to fix error in test (ParticipantView is a CrudView)
$participantView = new ParticipantView($mockDb);
$pv = $this
->getMockBuilder($participantView::class)
->onlyMethods(['find'])
->getMock();
$pv
->expects($this->once())
->method('find')
->willReturn([
'id' => '1234',
'ssn' => '555-12-3456',
'lastName' => 'Smith',
'firstName' => 'John',
'credentials' => 'foo'
]);
$this->assertEquals('John', $pv['firstName']);
}
}
yields
There was 1 error:
1) buildNewParticipantTest::testCredentialInclusion
ArgumentCountError: Too few arguments to function CrudView::__construct(), 0 passed
How do I pass a mock Database object into the mock ParticipantView object?