亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

PHPUnit Mock - 期望調用多個方法名稱中的 1 個

PHPUnit Mock - 期望調用多個方法名稱中的 1 個

PHP
溫溫醬 2023-03-26 13:57:03
我正在研究在服務中模擬記錄器類并確保它嘗試記錄錯誤。它遵循psr/log接口,因此可以通過多個路由實現錯誤記錄。調用error方法或log使用LogLevel::errorPHPUnit mocking 中有沒有辦法檢查這個。<?php// Create a mock logger that can be observed$logger = $this->createMock(LoggerInterface::class);// This fails is $logger->log(LogLevel::error, 'some message'); is called$logger    ->expects($this->once())    ->method('error');// This fail is $logger->error() is called$logger    ->expects($this->once())    ->method('log')    ->with(LogLevel::ERROR);上面的兩種方法都做同樣的事情,記錄錯誤,所以我真的不介意使用哪一種,只要使用一種即可。有沒有人對如何實現這一目標有任何想法?我已經看到有一種方法叫做$this->logicalOr()但我認為它不適合目的。提前謝謝大家!
查看完整描述

1 回答

?
鳳凰求蠱

TA貢獻1825條經驗 獲得超4個贊

得到這個工作。斷言在測試用例期間拋出并記錄異常。


測試與此類似的場景


<?php



class Service

{

    /**

     * @var \Psr\Log\LoggerInterface

     */

    protected $logger;



    public function setLogger(\Psr\Log\LoggerInterface $logger)

    {

        $this->logger = $logger;

    }


    public function doSomething($value)

    {

        try {

            $this->handleDoingSomething($value);

        }

        catch (Exception $e) {

            $this->logger->error($e->getMessage());


            // or optionally


            $this->logger->log(\Psr\Log\LogLevel::ERROR, $e->getMessage());


            throw $e;

        }

    }


    protected function handleDoingSomething($value)

    {

        throw new Exception();

    }

}

可以通過使用這樣的測試用例來實現


<?php


class ServiceTest extends \PHPUnit\Framework\TestCase

{

    public function testDoSomething()

    {

        $loggerCalledCount = 0;

        $loggerCallback = function ($methodParameter) use (&$loggerCalledCount) {

            $loggerCalledCount++;


            return true;

        };


        $logger = $this->createMock(\Psr\Log\LoggerInterface::class);

        $logger->method('error')->with($this->callback($loggerCallback));

        $logger->method('log')->with(\Psr\Log\LogLevel::ERROR, $this->callback($loggerCallback));


        $exceptionCaught = false;

        try {

            $service = new Service();

            $value = 'this value will trigger an exception if used';

            $service->doSomething($value);

        }

        catch (Exception $e) {

            $exceptionCaught = true;

        }


        $this->assertTrue($exceptionCaught);

        $this->assertGreaterThan(0, $loggerCalledCount);

    }

}


希望能幫助人們。


查看完整回答
反對 回復 2023-03-26
  • 1 回答
  • 0 關注
  • 126 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號