Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Str::shouldReceive? (mocking Illuminate\Support\Str)

I have a class that uses Str::random() which I would like to test.

But when I use Str::shouldReceive('random') in my test, I get a BadMethodCallException saying the method shouldReceive does not exist.

I also tried to mock the class directly and bind it to the IOC but it keeps executing the original class, generating a random string and not the return value I set on the mock.

    $stringHelper = Mockery::mock('Illuminate\Support\Str');
    $this->app->instance('Illuminate\Support\Str', $stringHelper);
    //$this->app->instance('Str', $stringHelper);

    $stringHelper->shouldReceive('random')->once()->andReturn('some password');
    //Str::shouldReceive('random')->once()->andReturn('some password');
like image 228
toonevdb Avatar asked Nov 22 '22 18:11

toonevdb


1 Answers

you could not use laravel Mock because Str::random() is not Facade. instead, you can create a new class with a method that set your test environment. like this: ‍‍‍

<?php

namespace App;


use Illuminate\Support\Str;

class Token
{
    static $testToken =null;
    public static function generate(){
        return static::$testToken ?:Str::random(60);
    }

    public static function setTest($string){
        static::$testToken = $string;
    }
}
like image 84
shayan Avatar answered Nov 29 '22 05:11

shayan