Skip to content

Instantly share code, notes, and snippets.

@heiglandreas
Created June 21, 2022 18:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save heiglandreas/70979dbf402e1983448f134b9c96093c to your computer and use it in GitHub Desktop.
Save heiglandreas/70979dbf402e1983448f134b9c96093c to your computer and use it in GitHub Desktop.
<?php
class ClassToTestA
{
public function __construct(private ClockInterface $clock) {}
public function do(): void
{
$a = $this->clock->now();
sleep(6);
$b = $this->clock->now();
if ($b->getTimestamp() - $a->getTimestamp() != 6) {
throw new Exception('broken');
}
}
}
<?php
class ClassToTestB
{
public function __construct(
private ClockInterface $clock,
private SleepInterface $sleep,
) {}
public function do(): void
{
$a = $this->clock->now();
$this->sleeper->sleep(6)
$b = $this->clock->now();
if ($b->getTimestamp() - $a->getTimestamp() != $this->sleeper->getSleep()) {
throw new Exception('broken');
}
}
}
<?php
class MockSleeper implements SleepInterface
{
public function __construct(private int $sleep) {}
public function sleep(int $sleep): void
{
// do nothing
}
public function getSleep(): int
{
return $this->sleep;
}
}
<?php
$mock = new MockClock([
new DateTimeImmutable('2022-06-21T12:23:34.000000Z'),
new DateTimeImmutable('2022-06-21T12:23:40.000000Z'),
]);
$foo = new ClassToTestA($mock);
$foo->do();
$bar = new ClassToTestB($mock, new MockSleeper(6));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment