Skip to content

Commit d4209dc

Browse files
committed
Add createCallback to AsyncTestCase
1 parent a72b1fa commit d4209dc

File tree

2 files changed

+29
-0
lines changed

2 files changed

+29
-0
lines changed

src/AsyncTestCase.php

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
namespace Amp\PHPUnit;
44

55
use Amp\Loop;
6+
use PHPUnit\Framework\MockObject\MockObject;
67
use PHPUnit\Framework\TestCase as PHPUnitTestCase;
78
use function Amp\call;
89

@@ -78,4 +79,23 @@ final protected function setTimeout(int $timeout)
7879

7980
Loop::unreference($this->timeoutId);
8081
}
82+
83+
/**
84+
* @param int $invocationCount Number of times the callback must be invoked or the test will fail.
85+
* @param callable|null $returnCallback Callable providing a return value for the callback.
86+
*
87+
* @return callable|MockObject Mock object having only an __invoke method.
88+
*/
89+
final protected function createCallback(int $invocationCount, callable $returnCallback = null): callable
90+
{
91+
$mock = $this->createMock(CallbackStub::class);
92+
$invocationMocker = $mock->expects($this->exactly($invocationCount))
93+
->method('__invoke');
94+
95+
if ($returnCallback) {
96+
$invocationMocker->willReturnCallback($returnCallback);
97+
}
98+
99+
return $mock;
100+
}
81101
}

test/AsyncTestCaseTest.php

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -89,4 +89,13 @@ public function testSetMinimumRunTime()
8989
$this->expectExceptionMessageRegExp("/Expected test to take at least 100ms but instead took (\d+)ms/");
9090
yield call($func);
9191
}
92+
93+
public function testCreateCallback()
94+
{
95+
$mock = $this->createCallback(1, function (int $value): int {
96+
return $value + 1;
97+
});
98+
99+
$this->assertSame(2, $mock(1));
100+
}
92101
}

0 commit comments

Comments
 (0)