【问题标题】:Cannot test a method that reference to mocking method PHPUnit无法测试引用模拟方法 PHPUnit 的方法
【发布时间】:2018-05-08 02:03:56
【问题描述】:

我正在使用模拟 PHPUnit 为我的代码创建模拟测试。 但是当我在类中创建一个由另一个方法(B)调用的模拟方法(A)时,方法 B 不会返回我想要的 - 它总是返回 null。

我的班级:

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

public function getAverageScore()
{
    // do something
}

我的测试:

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

错误:

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/"
        }
    }
}

【问题讨论】:

  • 为了更好地理解代码,请避免使用“幻数”,3, 5, ... 改用常量,例如 const MINIMUM_RECOMMENDED_RATE = 3
  • @FelippeDuarte 是的,我会在一切正常后重构它。

标签: php mocking phpunit stub


【解决方案1】:

没有理由模拟您正在测试的课程。 Mock 用于避免来自另一个对象或类的复杂、风险或昂贵的函数调用,您有一个已知响应,和/或您在另一个类中对其进行测试。

对于单元测试,您应该将应用程序置于可以测试所需场景的状态。

所以,你可以做类似的事情

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

【讨论】:

    猜你喜欢
    • 2017-02-27
    • 1970-01-01
    • 2013-08-18
    • 2022-08-22
    • 2012-05-13
    • 2022-08-05
    • 2013-01-27
    • 2011-10-30
    • 2016-07-20
    相关资源
    最近更新 更多