I am learning Codeception and I wonder when I should use setUp() or tearDown() and when I should use _before() or _after(). I don't see no difference. Both methods are run before or after a single test in my testfile? Thanks,
As Gabriel Hemming has mentioned, setUp() and tearDown() are PHPUnit's way of setting up the environment before each test is run and tearing down the environment after each test is run. _before() and _after() is how codeception's way of doing this.
To answer your question, about why codeception has different set of methods for this let me refer you to codeception's documentation: http://codeception.com/docs/05-UnitTests#creating-test
As you see, unlike in PHPUnit, the setUp and tearDown methods are replaced with their aliases: _before, _after.
The actual setUp and tearDown are implemented by the parent class \Codeception\TestCase\Test and set the UnitTester class up to have all the cool actions from Cept-files to be run as a part of your unit tests.
The cool actions the docs are referring to are any modules or helper classes that can now be used in your unit test.
Here is a good example of how to use modules in your unit test: http://codeception.com/docs/05-UnitTests#using-modules
Let's have an example of setting up fixture data in a unit test:
<?php
class UserRepositoryTest extends \Codeception\Test\Unit
{
/**
* @var \UnitTester
*/
protected $tester;
protected function _before()
{
// Note that codeception will delete the record after the test.
$this->tester->haveInDatabase('users', array('name' => 'miles', 'email' => 'miles@davis.com'));
}
protected function _after()
{
}
// tests
public function testUserAlreadyExists()
{
$userRepository = new UserRepository(
new PDO(
'mysql:host=localhost;dbname=test;port=3306;charset=utf8',
'testuser',
'password'
)
);
$user = new User();
$user->name = 'another name';
$user->email = 'miles@davis.com';
$this->expectException(UserAlreadyExistsException::class);
$user->save();
}
}
class User
{
public $name;
public $email;
}
class UserRepository
{
public function __construct(PDO $database)
{
$this->db = $database;
}
public function save(User $user)
{
try {
$this->db->prepare('INSERT INTO `users` (`name`, `email`) VALUES (:name, :email)')
->execute(['name' => $user->name, 'email' => $user->email]);
} catch (PDOException $e) {
if ($e->getCode() == 1062) {
throw new UserAlreadyExistsException();
} else {
throw $e;
}
}
}
}