【问题标题】:Use a Mock PHPUnit in non-test class在非测试类中使用 Mock PHPUnit
【发布时间】:2017-10-14 09:24:52
【问题描述】:

对于一个项目,我必须模拟一个类,并且我想在我的代码中使用这个模拟来模拟一种行为。 在我的测试类中,我输入了这段代码:

public function testExportCsv()
{
    $mockObject = $this->getMockBuilder('\Client')
        ->setConstructorArgs(array("0"))
        ->getMock();
    $res = $this->searchDocApiDocumentsStub();
    $mockObject->method('searchDocuments')
        ->willReturn($res);
}

public function searchDocApiDocumentsStub()
{
    $res = array();
    $yml = Yaml::parse(file_get_contents("../src/ExportCSVBundle/Resources/config/generic.yml"));
    $typeDoc = "FAC";
    $metas[$typeDoc] = $yml["ETT"][strtoupper($typeDoc)];


    foreach ($this->documents as $document) {
        if ($document["type"] == "DocumentsAPI\\Model\\" . str_replace('$eq ', '', $typeDoc)) {
            foreach ($metas[$typeDoc] as $field) {
                $docres[] = $document["metas"][$field];
            }
            $res = array_merge($res, $docres);
        }
    }
    return $res;
}

在另一个类“导出”中,我必须使用我模拟的类,在属性中,这个类有一个“客户端”对象,即我模拟的类。 然后我必须使用这个对象。

class Export {
    public function __construct(Client $docApiClient)
    {
        $this->docApiClient = $docApiClient;
    }

    $docs = $this->docApiClient->searchDocuments($client, $query, null, false, false, $metasToExport);

我希望这个“searchDocuments”成为我制作的存根。

$export = new \ExportLibraryBundle\ExportLibrary\Export(//What Do I put ??);

我不知道我是否清楚,但感谢您的帮助。

【问题讨论】:

  • 但是我的 mockObject 在一个测试类中,我如何将它注入到我的类“Export”中?

标签: mocking phpunit stub


【解决方案1】:

似乎 PHPUnit 的默认模拟引擎强烈依赖于 PHPUnit itselt。

如果你想在 PHPUnit 测试之外使用模拟,你可以使用外部模拟库,即。嘲讽。它非常相似,除了它不依赖于 PHPUnit 并且有一些 PHPUnit Mocks 没有的强大功能(即 demeter 链模拟)。

http://docs.mockery.io/en/latest/

您可以在此处查看一些示例和比较:https://code.tutsplus.com/tutorials/mockery-a-better-way--net-28097

【讨论】:

  • 谢谢,我会检查的!
猜你喜欢
  • 2014-02-08
  • 1970-01-01
  • 2015-04-04
  • 2017-10-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-12-31
  • 1970-01-01
相关资源
最近更新 更多