Skip to content

Commit

Permalink
MockBuilder method to verify mock method existence
Browse files Browse the repository at this point in the history
  • Loading branch information
DFoxinator committed May 9, 2019
1 parent ba3417f commit ff787e6
Show file tree
Hide file tree
Showing 2 changed files with 53 additions and 0 deletions.
25 changes: 25 additions & 0 deletions src/Framework/MockObject/MockBuilder.php
Expand Up @@ -178,6 +178,31 @@ public function setMethods(array $methods = null): self
return $this;
}

/**
* Specifies the subset of methods to mock, requiring each to exist in the class
*/
public function setRealMethods(array $methods = null): self
{
if ($methods) {
$reflection = new \ReflectionClass($this->type);

foreach ($methods as $method) {
if (!$reflection->hasMethod($method)) {
throw new RuntimeException(
\sprintf(
'Trying to set mock method "%s" which cannot be configured because it does not exist',
$method
)
);
}
}
}

$this->methods = $methods;

return $this;
}

/**
* Specifies the subset of methods to not mock. Default is to mock all of them.
*/
Expand Down
28 changes: 28 additions & 0 deletions tests/unit/Framework/MockObject/MockBuilderTest.php
Expand Up @@ -51,6 +51,34 @@ public function testMethodExceptionsToMockCanBeSpecified(): void
$this->assertNull($mock->anotherMockableMethod());
}

public function testSetMethodsAllowsNonExistentMethodNames(): void
{
$mock = $this->getMockBuilder(Mockable::class)
->setMethods(['mockableMethodWithCrazyName'])
->getMock();

$this->assertNull($mock->mockableMethodWithCrazyName());
}

public function testSetRealMethodsWithNonExistentMethodNames(): void
{
$this->expectException(RuntimeException::class);

$this->getMockBuilder(Mockable::class)
->setRealMethods(['mockableMethodWithCrazyName'])
->getMock();
}

public function testSetRealMethodsWithExistingMethodNames(): void
{
$mock = $this->getMockBuilder(Mockable::class)
->setRealMethods(['mockableMethod'])
->getMock();

$this->assertNull($mock->mockableMethod());
$this->assertTrue($mock->anotherMockableMethod());
}

public function testEmptyMethodExceptionsToMockCanBeSpecified(): void
{
$mock = $this->getMockBuilder(Mockable::class)
Expand Down

0 comments on commit ff787e6

Please sign in to comment.