【问题标题】:PHPUnit expect call with one parameter - describe the parameter in more detailPHPUnit 期望调用一个参数 - 更详细地描述参数
【发布时间】:2018-01-19 15:42:14
【问题描述】:

我有以下 phpunit 模拟:

    $this->httpClient->expects($this->at(1))->method('send')
        ->with($this->isInstanceOf(RequestInterface::class))
        ->willReturn($responseMock);

因此,“with”函数调用正在检查的“send”方法的参数必须是 RequestInterface 的实例。但是我需要更详细地检查这个参数:

  • 必须是 RequestInterface 实例的对象
  • 对象的“url”属性需要有一定的值(比如“https://some-domain.com”)
  • 并且对象的方法必须是'GET'

我该怎么做?

【问题讨论】:

    标签: php phpunit


    【解决方案1】:

    您可以使用 PHPUnit 的 callback constraint 为您的断言添加自定义逻辑,例如

    $this->httpClient
        ->expects($this->at(1))->method('send')
        ->with($this->callback(function (RequestInterface $request) {
            $this->assertSame('https://some-domain.com', $request->getUri());
            $this->assertSame('GET', $request->getMethod());
    
            return true;
        }))
        ->willReturn($responseMock);
    

    如果传递的对象应该被认为是有效的,则回调应该返回 true,但是您也可以在其中使用本机断言(assertSame 等) - 这些引发的任何异常都会冒泡到测试本身。此处的 instanceof 检查由回调上的类型提示处理,因为如果不匹配,将引发 TypeError。如果您愿意,也可以省略类型提示并手动运行 assertInstanceOf

    (注意:我假设您在这里使用PSR-7 RequestInterface - 显然,如果没有,回调中的方法名称将需要更改。)

    【讨论】:

    • 像魅力一样工作。谢谢!该请求符合 PSR-7 标准,因此非常适合。
    猜你喜欢
    • 2015-09-17
    • 1970-01-01
    • 2020-08-14
    • 2023-03-09
    • 2016-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多