Home > Blockchain >  How to stub/mock return value of a function in php unit test
How to stub/mock return value of a function in php unit test

Time:12-30

When trying to stub a simple function based on the phpunit documentation here, it doesn't seem to do anything.

<?php declare(strict_types=1);

class A {

    public static function func() {
        $helperData = A::helper();
        return $helperData   1;
    }

    public static function helper() {
        return 5;
    }
}

Test class

<?php declare(strict_types=1);
use PHPUnit\Framework\TestCase;

final class ATest extends TestCase
{
    public function testFunc(): void
    {
        $stub = $this->createStub(A::class);
        $stub->method('helper')
        ->willReturn(2);

       $result = A::func();
       $this->assertEquals(3, $result); // actual result is 6 not 3--why?
    }
}

The stubbed function helper doesn't return 2 as I specified. Why is this, and how can I successfully mock the return value of the function?

CodePudding user response:

You should use $stub object instead of A class, to get the stubbed function result. You should use non-static method to use this.

<?php 

declare(strict_types=1);

use PHPUnit\Framework\TestCase;

class A {

    public function func() {
        $helperData = $this->helper();
        return $helperData   1;
    }

    public function helper() {
        return 5;
    }
}

final class ATest extends TestCase
{
    public function testFunc(): void
    {
        $stub = $this->createStub(A::class);

        $stub->method('helper')
            ->willReturn(2);

        $stub->method('func')
            ->willReturn($stub->helper()   1);

        
        $result = $stub->func(); // Use `$stub->`
        $this->assertEquals(3, $result); // OK
    }
}

Output:

OK (1 test, 1 assertion)

EDIT


To use the original code for func, you could make it static, and use a A instance as parameter. This A instance could be $stub (because $stub is a A&Stub instance).



class A {

    public static function func(A $obj) {
        $helperData = $obj->helper();
        return $helperData   1;
    }

    public function helper() {
        return 5;
    }
}

final class ATest extends TestCase
{
    public function testFunc(): void
    {
        $stub = $this->createStub(A::class);

        $stub->method('helper')
            ->willReturn(2);

        $result = A::func($stub);
        $this->assertEquals(3, $result);
    }
}

Output:

OK (1 test, 1 assertion)
  • Related