PHPUnit不能模拟类

时间:2018-07-31 04:53:51

标签: php unit-testing phpunit

我遇到一个问题,PHPUnit无法模拟我的简单类:

class.php

<?php
    class SUT {
    function doThing() {
        $db = new DB();
        return $db->query();
    }
}

class DB {
    function query() {
        return "failed";
    }
}
?>

test.php

<?php
use PHPUnit\Framework\TestCase;
require 'API/class.php';

class SampleTest extends TestCase {

    public function testTest() {
        $db = $this->createMock(DB::class);
        $db->method('query')
            ->willReturn("win");

        $sut = new SUT();
        $result = $sut->doThing();
        $this->assertEquals("win", $result);
    }

}

输出:

PHPUnit 5.7.21 by Sebastian Bergmann and contributors.
Runtime:       PHP 7.1.16
Configuration: ~/API_tests/config.xml

F...............                                                  16 / 16 (100%)

Time: 604 ms, Memory: 10.00MB
There was 1 failure:

1) SampleTest::testTest
Failed asserting that two strings are equal.
--- Expected
+++ Actual
@@ @@
-'win'
+'failed'

~/API_tests/TestTest.php:14

我在这里缺少基本的东西吗?我是否需要将模拟对象传递给SUT?

1 个答案:

答案 0 :(得分:0)

这是因为您直接在doNothing方法中实例化了DB类。这意味着您不使用自己创建的模拟。您可以使用依赖注入来达到预期的结果。只需将数据库实例作为依赖项传递到SUT::__constructor()中,它将起作用。

class.php     

class SUT
{
    /** @var DB */
    private $db;

    public function __construct(DB $db) {
        $this->db = $db;
    }

    function doThing()
    {
        return $this->db->query();
    }
}

class DB
{
    function query()
    {
        return "failed";
    }
}

test.php

<?php

use PHPUnit\Framework\TestCase;

require 'API/class.php';

class SampleTest extends TestCase
{

    public function testTest()
    {
        $db = $this->createMock(DB::class);
        $db->method('query')
            ->willReturn("win");

        $sut = new SUT($db);
        $result = $sut->doThing();
        $this->assertEquals("win", $result);
    }

}