Search code examples
phpmockingphpunitstub

Cannot test a method that reference to mocking method PHPUnit


I'm using mocking PHPUnit to create a mock test for my code. But when I create a mock method(A) which is called by another method(B) in class, method B not return what I want - it always return null.

My class:

public function isRecommended()
{
    return $this->getAverageScore() >= 3;
}

public function getAverageScore()
{
    // do something
}

My Test:

public function testIsRecommended_With5_ReturnsTrue()
{
    $game = $this->createMock(Game::class);
    $game->method('getAverageScore')->willReturn(5); //mocking return 5
    $this->assertTrue($game->isRecommended());
}

Error:

1) Src\Tests\Unit\GameTest::testIsRecommended_With5_ReturnsTrue
Failed asserting that null is true.

composer.json

{
    "require": {
        "phpunit/phpunit": "^7.1",
        "phpunit/phpunit-mock-objects": "^6.1"
    },
    "autoload": {
        "psr-4": {
            "Src\\": "src/",
            "Tests\\": "tests/"
        }
    }
}

Solution

  • There is no reason to mock the class you are testing. Mock is used to avoid complex, risk or expensive function call from another object or class, that you have a know response, and/or you test it in another class.

    For unit tests, you should put the application in a state that you can test the desired scenario.

    So, you can do something like

    public function testIsRecommended_With5_ReturnsTrue()
    {
        $game = new Game;
        $game->addScore(10);
        $game->addScore(0); //average score 5
        $this->assertTrue($game->isRecommended()); //5 > 3
    }