如何使用PHPUnit从头开始创建一个假类?

时间:2016-12-02 09:26:25

标签: php unit-testing mocking phpunit

我目前需要测试一个方法,该方法使用PHPUnit检查类是否存在提供的方法。

目前我只是在单元测试中创建一个空类,它工作正常。我猜可能有更好的解决方案。这是我目前正在运行的代码:

class ControllerMiddleWareTest extends TestCase
{
    /**
     * Check to see if a faulty method name leads to a MethodNotFoundException.
     */
    public function testShouldMethodNotFoundException()
    {
        $this->expectException(MethodNotFoundException::class);

        $parameterBag = new Bag(['lang' => 'NL']);

        // This class name(and method) should never exist.
        new ControllerMiddleware('AwesomeController', 'init', $parameterBag);
    }
}

// Mock class so we get a MethodNotFoundException.
class AwesomeController{}

我已经找到了很多例子,其中现有的类被模拟,但不是像这样创建类的地方。我该怎么做呢?

1 个答案:

答案 0 :(得分:0)

找到解决方案:

$this->getMockBuilder('AwesomeController')->getMock();

如果有其他人知道更好的方法或有任何建议,我会很高兴听到它。