Search code examples
phplaravelmockery

Testing a simple function in a model with Mockery


I'm totally new with Mockery which is embedded in Laravel. I have the pain to test a simple model function which increments a portion of a reference, whatever the value I'm passing to test the result is ok even when it should fail. I think I made an error somewhere or I don't understand the documentation. Thanks for your help.

Here is the simple function to test

public function incrementRefFormation(string $value):string
{
    $split = str_split($value);
    $group1 = '';

    for ($i=0;$i<11;$i++) {
        $group1 .= $split[$i];
    }

    $group2 = $split[11].$split[12];
    $group2 = (int)$group2;
    $group2++;

    return $group1.$group2.$split[13];
}

Here is the test which should fail

public function testIncrementRefFormation()
{
    //$testValue = '1 332 8100 20S';
    $testValue = '123456';
    $expectedValue = '1332810021S';


    $mock = Mockery::mock('App\Models\Formation');

    $mock->shouldReceive(['incrementRefFormation' => $expectedValue])
            ->once();

    var_dump($mock->incrementRefFormation($testValue));
}

Many thanks!


Solution

  • Mockery is used for creating 'mocks', which are dumb objects doing only what you tell them to do (e.g. method x will return y if supplied with parameter z). Usually it's used for mocking dependencies of the class you want to test. In your case you probably won't need it.

    So your test would probably look something like this

    $formation = new App\Models\Formation();
    $actualvalue = $formation->incrementRefFormation($testValue);
    $this->assertEquals($expectedValue, $actualvalue);