Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use the method setup from PHPUnit in Laravel 5.8

I used to use the method setup of PHPUnit to create a instance for my test methods. But in Laravel 5.8 I can't do it

I've tried both ways, and it's works makes an instance per method how showed below.

This works:

<?php

namespace Tests\Unit;

use Tests\TestCase;
use Illuminate\Foundation\Testing\WithFaker;
use Illuminate\Foundation\Testing\RefreshDatabase;
use App\Service\MyService;

class MyServiceTest extends TestCase
{
    /**
     * A basic unit test example.
     *
     * @return void
     */
    public function testInstanceOf()
    {
        $myService = new MyService;
        $this->assertInstanceOf( 'App\Service\MyService' , $myService );
    }
}


This doesn't works:

<?php

namespace Tests\Unit;

use Tests\TestCase;
use Illuminate\Foundation\Testing\WithFaker;
use Illuminate\Foundation\Testing\RefreshDatabase;
use App\Service\MyService;

class MyServiceTest extends TestCase
{

    private $instance;

    function setUp(){    
      $this->instance = new MyService;
    }
    /**
     * A basic unit test example.
     *
     * @return void
     */
    public function testInstanceOf()
    {
        $myService = $this->instance;
        $this->assertInstanceOf( 'App\Service\MyService' , $myService );
    }
}

This error message below show in console:

PHP Fatal error:  Declaration of Tests\Unit\MyServiceTest::setUp() must be compatible with Illuminate\Foundation\Testing\TestCase::setUp(): void in /home/myproject/tests/Unit/MyServiceTest.php on line 10

like image 882
Saulo Campos Avatar asked Aug 20 '19 22:08

Saulo Campos


2 Answers

Laravel 5.8 added the void typehint to the return type of the setUp method.
So you have to declare that like this:

public function setUp(): void
{
    // you should also call parent::setUp() to properly boot
    // the Laravel application in your tests
    $this->instance = new MyService;
}

Note the : void after the function arguments to state the return type of that function

like image 145
mdexp Avatar answered Sep 22 '22 00:09

mdexp


This is what i did and it help

/**
     * Set up the test
     */
    public function setUp(): void
    {
        parent::setUp();
        $this->faker = Faker::create();
    }

    /**
     * Reset the migrations
     */
    public function tearDown(): void
    {
        $this->artisan('migrate:reset');
        parent::tearDown();
    }

Not stating the return type to void in the functions

like image 25
Abednego Avatar answered Sep 20 '22 00:09

Abednego