What is setup (), beforeEach, teardown and afterEach in PHP/Laravel testing

image
image
image
image
image
image

What is setup (), beforeEach, teardown and afterEach in PHP/Laravel testing

SetUp (), BeforeEach

SetUp(), and before runs before each test is run in a specific PHPUnit test file.

But the difference is setup () is used in the PHPUnit tests. And the beforeEach is used in the PEST test.

Example for beforeEach

beforeEach(function () {
   $this->hey = rasif;
});

it('has artisan', function () {
   echo $this->hey;
});

// OutPut - rasif

SetUp () example

<?php declare(strict_types=1);
use Test\TestCase;

final class OpenDesk extends TestCase
{
    private $stack;

    protected function setUp(): void
    {
        $this->stack = [];
    }

    public function testEmpty(): void
    {
        $this->assertTrue(empty($this->stack));
    }

    public function testPush(): void
}

TearDown and AfterEach Methods

teardown() and afterEach functions run after each test is run in a specific test file.

But the difference is teardown() is used in the PHPUnit test and beforeEach is used in the PEST test.

But keep in mind you should write this function at the last of your test file.

Example for AfterEach

<?php
 
afterEach(function () {
    echo 'afterEach';
});
 
test('foo', function () {
    echo 'OpenDesk';
});
 
test('bar', function () {
    echo 'OpenDesk';
});
 
// OpenDesk
// afterEach
// OpenDesk
// afterEach

Thanks for reading If you need any updated information about this article please feel free to request in the comments section.

Get in Touch

Subscribe Our Newsletter

Your email address will not be published. Required fields are marked *

* indicates required