簡體   English   中英

PHPUnit willReturnMap 總是返回 null

[英]PHPUnit willReturnMap always returns null

我有一個使用以下模擬 class 的單元測試

$this->stubHandle = $this->getMockBuilder(Handle::class)->disableOriginalConstructor()->getMock();

當我跑

$key = new Key($this->stubHandle);
$this->stubHandle->method('__call')->will($this->returnCallback('var_dump'));
$key->nonExistingMethod('element0', 'element1', []);

它輸出

string(17) "nonExistingMethod"

array(3) {
  [0] =>
  string(8) "element0"
  [1] =>
  string(8) "element1"
  [2] =>
  array(0) {
  }
}

我認為這意味着方法__call的第一個參數是一個字符串,第二個參數是一個數組。 不再通過 arguments。

當我模擬方法__call的返回值時

$this->stubHandle->method('__call')->willReturn(1);

如預期的那樣,返回值始終為1

當我模擬方法__call的返回值時

$this->stubHandle->method('__call')->willReturnMap(
    [
        ['argument1', null, 'returnValue'],
    ]
);

當方法__call的第一個參數是'argument1'而第二個參數不關心時,我希望返回值是'returnValue' 如果第一個參數不是'argument1' ,我希望返回值null

這些預期是否正確?

無論我嘗試什么,當我使用方法willReturnMap null

如果我的期望是錯誤的,請引導我找到一種方法來實現我的目標來模擬返回值,這取決於第一個參數(僅)並向我解釋如何應用 willReturnMap。

看來我對方法willReturnMap的搜索有點誤導我。
我假設在 map 中使用null ,它會充當“不關心”,但它的字面意思是null

$this->stubHandle->method('__call')->willReturnMap(
    [
        ['nonExistingMethod', null, 'returnValue'],
    ]
);

表示方法__call的 arguments 必須明確為'nonExistingMethod' & null如果您希望返回值為'returnValue' 任何其他參數值將改為返回null
例如$key->nonExistingMethod(null);

對於 map 在我的示例中返回'returnValue' ,它應該是:

$this->stubHandle->method('__call')->willReturnMap(
    [
        ['nonExistingMethod', ['element0', 'element1', []], 'returnValue'],
    ]
);
$key->nonExistingMethod('element0', 'element1', []);

簡而言之......當使用參數映射時,這些值不能是“無關緊要”。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM