| title | Setup and Teardown |
|---|---|
| description | Setup and Teardown |
In your tests, you may want to run some code before and after each test or file. In this section, we'll discuss the globally available functions that allow you to do that.
Here you can find a list available setup/teardown functions.
The function beforeEach() runs the given closure before each test
in the current file.
It's the equivalent to
setUpin PHPUnit.
<?php
beforeEach(function () {
echo 'beforeEach';
});
test('foo', function () {
echo 'test foo';
});
test('bar', function () {
echo 'test bar';
});
// beforeEach
// test foo
// beforeEach
// test barAs usual, the $this variable in the beforeEach function
is bound to the current Test Case object. Therefore, you can share data
with both it and test functions.
beforeEach(function () {
$this->hey = 'artisan';
});
it('has artisan', function () {
echo $this->hey;
});
// artisanThe function afterEach() runs the given closure after each test
in the current file.
It's the equivalent to
tearDownin PHPUnit.
<?php
afterEach(function () {
echo 'afterEach';
});
test('foo', function () {
echo 'test foo';
});
test('bar', function () {
echo 'test bar';
});
// test foo
// afterEach
// test bar
// afterEachThe function beforeAll() runs the given closure before
all tests in the current file.
It's the equivalent to the
@beforeClassannotation in PHPUnit.
<?php
beforeAll(function () {
echo 'beforeAll';
});
test('foo', function () {
echo 'test foo';
});
test('bar', function () {
echo 'test bar';
});
// beforeAll
// test foo
// test barThe function afterAll() runs the given closure after
all tests in the current file.
It's the equivalent to the
@afterClassannotation in PHPUnit.
<?php
afterAll(function () {
echo 'afterAll';
});
test('foo', function () {
echo 'test foo';
});
test('bar', function () {
echo 'test bar';
});
// test foo
// test bar
// afterAllTo understand the order of execution of all those functions, let's take a look at the example below:
beforeAll(fn () => dump('beforeAll'));
afterAll(fn () => dump('afterAll'));
beforeEach(fn () => dump('beforeEach'));
afterEach(fn () => dump('afterEach'));
test('example 1', fn () => dump('test foo'));
test('example 2', fn () => dump('test bar'));
// "beforeAll"
// "beforeEach"
// "test foo"
// "afterEach"
// "beforeEach"
// "test bar"
// "afterEach"
// "afterAll"Next section: Higher Order Tests →