【问题标题】:How to create a fake class from scratch with PHPUnit?如何使用 PHPUnit 从头开始​​创建一个假类?
【发布时间】:2016-12-02 09:26:25
【问题描述】:

我目前需要测试一个方法,该方法检查一个类是否存在使用 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{}

我发现了很多示例,其中模拟了现有类,但没有像这样创建类。我该如何正确地做到这一点?

【问题讨论】:

标签: php unit-testing mocking phpunit


【解决方案1】:

找到解决方案:

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

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

【讨论】:

  • $this->createMock(AwesomeController::class) 将是最佳做法。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-05-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-05
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多