dongmin4052 2016-01-17 00:11
浏览 32
已采纳

可以不覆盖PHPUnit测试存根方法吗?

In my tests, I created a test stub for a class and mock the output of the method "save" to return a default value. I have this in my setUp() method to initiate before each test runs:

//  auth adapter
$this->authMock = $this->getMockBuilder('App\\Auth')
    ->disableOriginalConstructor()
    ->getMock();

// by defaut, we'll make authenticate return a FAIL result
$this->authMock
    ->method('authenticate')
    ->willReturn(0);

This is then inject into my service locator overwriting the one used by the app (the real App\Auth). However, during the actual tests, I may wish to change the output of that method

// here, we'll make authenticate return a SUCCESS result
$this->authMock
    ->method('authenticate')
    ->willReturn(1);

Anyway, once I identified the issue, for POC, I just put these one after the other and right enough it seems that PHPUnit doesn't allow me to overwrite the previously declared mocked method return value:

//  auth adapter
$this->authMock = $this->getMockBuilder('App\\Auth')
    ->disableOriginalConstructor()
    ->getMock();

// by defaut, we'll make authenticate return a FAIL result
$this->authMock
    ->method('authenticate')
    ->willReturn(0);

// here, we'll make authenticate return a SUCCESS result
$this->authMock
    ->method('authenticate')
    ->willReturn(1);

var_dump($this->authMock->authenticate()); exit; // returns 0 :(

I'm sure in the past I was able to do this. Unless it was a previous version of PHPUnit. Currently I'm using 4.8.*. Any way I can do this? By default I want authenticate to return FAIL, but some tests I may want to override this with SUCCESS (so act as though the user is authenticated)

  • 写回答

1条回答 默认 最新

  • dse3168 2016-01-17 00:49
    关注

    I can't recall ever being able to mock the same method twice, so what I usually do is define a helper function:

    protected function mockAuthResult($result = 0) {...}
    

    Another option would be to define:

    protected $authResult;
    

    And then in your setUp:

    $this->authResult = 0; // fail by default
    $this->authMock
        ->method('authenticate')
        ->willReturn($this->authResult);
    

    And then you can override it for individual tests.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同
  • ¥50 如何openEuler 22.03上安装配置drbd
  • ¥20 ING91680C BLE5.3 芯片怎么实现串口收发数据
  • ¥15 无线连接树莓派,无法执行update,如何解决?(相关搜索:软件下载)
  • ¥15 Windows11, backspace, enter, space键失灵