質問が出されてから 8 年後、最初に回答されてから 5 年後、私は同じ質問をして同様の結論に達しました。これは私が行ったことであり、基本的にはDavidの受け入れられた回答の2番目の部分と同じですが、PHPUnitの新しいバージョンを使用しています。
基本的に、ArrayAccess
インターフェイス メソッドをモックできます。offsetGet
と の両方をモックしたい可能性があることを覚えておく必要がありますoffsetExists
(配列キーを使用する前に、その存在を常に確認する必要があります。そうE_NOTICE
しないと、コードが存在しない場合にエラーや予期しない動作が発生する可能性があります)。
$thingyWithArrayAccess = $this->createMock(ThingyWithArrayAccess::class);
$thingyWithArrayAccess->method('offsetGet')
->with('your-offset-here')
->willReturn('test-value-1');
$thingyWithArrayAccess->method('offsetExists')
->with($'your-offset-here')
->willReturn(true);
もちろん、次のように、テストで実際の配列を使用することもできます。
$theArray = [
'your-offset-here-1' => 'your-mock-value-for-offset-1',
];
$thingyWithArrayAccess = $this->createMock(ThingyWithArrayAccess::class);
$thingyWithArrayAccess->method('offsetGet')
->willReturnCallback(
function ($offset) use ($theArray) {
return $theArray[$offset];
}
);
$thingyWithArrayAccess->method('offsetExists')
->willReturnCallback(
function ($offset) use ($theArray) {
return array_key_exists($offset, $theArray);
}
);