Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

jay_singulara_tech's avatar

Error in unit test when using setUp() function

Getting an error after I add the setUp() function. Also, PHPStorm puts a red underline below the setUp() function name. The code looks to me, exactly like in the lesson but... I get this error from PHPUnit

Fatal error: Declaration of Tests\Unit\UserTest::setUp() must be compatible with Illuminate\Foundation\Testing\TestCase::setUp(): void in C:\Projects\MyProject\tests\Unit\UserTest.php on line 15

0 likes
9 replies
jay_singulara_tech's avatar

Here is the code


<?php

namespace Tests\Unit;

use Tests\TestCase;
use Illuminate\Foundation\Testing\DatabaseTransactions;
use App\User;

class UserTest extends TestCase
{
    use DatabaseTransactions;

    protected $user;
    
    public function setUp() {
        parent::setUp();
        $this->user = factory(User::class)->state('enabled')->create();
    }
    
    /**
     * @test
     * @return void
     */
    public function it_can_be_enabled()
    {
        $value = $this->user->enabled()->pluck('is_enabled')->first();
        $this->assertEquals(1, $value);
    }
}

The test itself was passing before adding the setup function. Any help will be appreciated as, I am stuck on the lesson, for now. Thanks in advance.

4 likes
jay_singulara_tech's avatar

I found it. Hope this helps someone else. This works. public function setUp() :void {

The code in the lesson was wrong or outdated, I guess. This fails. public function setUp() {

45 likes
patgilmour's avatar

I think the colon is in the wrong place in the solution above. It didn't work for me. Here's an example derived from the php-unit docs to skip a test that works on Laravel 6/PHP 7.3:

    protected function setUp(): void
    {
        $this->markTestSkipped(
            'This test will be skipped when you run `php-unit`.'
        );
    }
2 likes
acilento's avatar

The colon works in both places to me. I am using PHP 7.4.5.

codingstuff91's avatar

Thanks a lot i had the same issue and thanks to you i applied a solution that works

Please or to participate in this conversation.