Skip to content

Instantly share code, notes, and snippets.

@ciaranmcnulty
Last active March 15, 2019 20:34
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ciaranmcnulty/a23e90006f2b9338771b7299c362c235 to your computer and use it in GitHub Desktop.
Save ciaranmcnulty/a23e90006f2b9338771b7299c362c235 to your computer and use it in GitHub Desktop.
Contract tests example
<?php
class DoctrineUserRepositoryTest extends UserRepositoryTest
{
public function setUp()
{
// do something to bootstrap doctrine and set up DB fixtures
$this->userRepository = new DoctrineRepository(/* lots of dependencies */);
}
public function tearDown()
{
// do something to clean up DB
}
}
<?php
class InMemoryUserRepository implements UserRepository
{
private $users = [];
public function create(User $user) : void
{
if ($this->findByEmail($user->email())) {
throw new DuplicateUserException();
}
$this->users[] = $user;
}
public function findByEmail(string $email) : ?User
{
foreach ($users as $user) {
if ($user->email() == $email) {
return $user;
}
}
}
}
<?php
class InMemoryUserRepositoryTest extends UserRepositoryTest
{
public function setUp()
{
$this->userRepository = new InMemoryUserRepository();
}
// don't put any tests here
}
<?php
interface UserRepository
{
/** @throws DuplicateUserException */
public function create(User $user) : void;
public function findByEmail(string $email) : ?User;
}
<?php
/** Contract tests for any well-behaved UserRepository */
abstract class UserRepositoryTest extends TestCase
{
/** @var UserRepository */
protected $userRepository;
function testItStoresAUser()
{
$user = new User(/* ... */, 'ciaran@crania.uk');
$this->userRepository->create($user);
$this->assertEquals($this->userRepository->findByEmail('ciaran@crania.uk');
}
function testItReturnsNullWhenNoUser()
{
$this->assertNull($this->userRepository->findByEmail('nobody@doesNotExist.com'));
}
function testItDoesNotAllowDuplicateEmails()
{
$user = new User(/* ... */, 'ciaran@crania.uk');
$this->userRepository->create($user);
$this->setExpectedException(DuplicateUserException::class);
$user2 = new User(/* ... */, 'ciaran@crania.uk');
$this->userRepository->create($user2);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment