cactus's avatar
Level 15

How to write a test case for Traits

I have a trait RandomTrait. I want to write a test case for this trait. How can I do that?

I am creating a new class and then using the said trait in that class & writing the test cases for the new class.

However, when I run the test case, I see the error

PHP Fatal error:  Class 'DB' not found in /var/www/crm/app/Traits/RandomTrait.php

Code:

RandomTrait.php

<?php namespace App\Traits;

use DB;

trait RandomTrait
{
    public function randomFunction()
    {
        return DB::table('my_table')
                             ->select('name')
                             ->first();

    }
}

RandomTraitTest.php

<?php

use Illuminate\Foundation\Testing\WithoutMiddleware;
//use Illuminate\Foundation\Testing\DatabaseMigrations;
//use Illuminate\Foundation\Testing\DatabaseTransactions;
use App\Traits\RandomTrait;


/**
 * Created a class as a wrapper to test the trait
 */
class RandomTest
{
    
    use RandomTrait;
}

/**
 * Actual test cases
 */
class RandomTraitTest extends TestCase
{

    use WithoutMiddleware;

    public $dummy;

    public function setUp()
    {
        $this->dummy = new RandomTest();
       
    }

    /**
     * @test
     */
    public function should_return_random_name()
    {
        $randomName = $this->dummy->randomFunction();
        print_r($randomName);
    }
}

0 likes
1 reply

Please or to participate in this conversation.