これが私のクラスです:
public function __construct(Manager $moduleManager, Source\Yesno $yesNo)
{
$this->moduleManager = $moduleManager;
$this->yesNo = $yesNo;
}
public function my1()
{
$this->moduleManager->isOutputEnabled('');
$this->yesNo->toOptionArray();
}
public function my2()
{
$this->moduleManager->isOutputEnabled('');
$this->yesNo->toOptionArray();
}
これが私のテストです:
...
$this->observerMock = $this->getMock(
'path\to\Observer',
null,
[$this->moduleManagerMock, $this->yesNoMock],
'',
true
);
...
public function testMy1()
{
$this->moduleManagerMock->expects($this->exactly(2))->method('isOutputEnabled');
$this->yesNoMock->expects($this->exactly(2))->method('toOptionsArray');
$this->observerMock->my1();
$this->observerMock->my2();
}
テスト結果:
メソッド名の期待に失敗しましたが、2 回呼び出されたときと同じです。メソッドは 2 回呼び出されると予想されていましたが、実際には 0 回呼び出されました。
私の質問は次のとおりです。私はそのようなことに数回直面しましたが、何が起こっているのか理解できません。なぜ最初の期待は適切で、2 番目の期待は適切ではないのですか?
更新1
私はそのような状況に数回直面したことを忘れていました。これが私が気づいたことです。xDebugを使用して、テスト内でそれを見ました
[this]
[moduleManager] => ModuleManager_Mock_Name_<hash #1>
[yesNo] => YesNo_Mock_Name_<hash #2>
[observerObject] =>
[moduleManager] => ModuleManager_Mock_Name_<hash #1>
[yesNo] => YesNo_Mock_Name_<hash #3> <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
moduleManager オブジェクトは、unittest オブジェクト内とオブザーバー オブジェクト内に同じキャッシュを持ちます。moduleMatcher に smth を適用すると、両方の場所に表示されます
$unittest->yesNo のハッシュは $observerObject のハッシュとは異なります。いくつかのメソッドにマッチャーを設定すると、ユニットテストクラス内でのみ適用されます!!!
なぜそれが起こったのですか?別のオブジェクトを作成しないようにする方法
Upd.2 見つかりました!
オブジェクトマネージャでオブジェクトを作成する場合
$this->observerMock = $objectManager->getObject(
'Observer',
[
'moduleManager' => $this->moduleManagerMock,
'yesNo' => $this->yesNoMock,
]
);
変数「moduleManager」および「yesNo」は、コンストラクターの変数と同じである必要があります。
public function __construct(Manager $moduleManager, Source\Yesno $yesNo)
{
$this->moduleManager = $moduleManager;
$this->yesNo = $yesNo;
}
phpunit がこれをチェックするコードは次のとおりです。
foreach ($method->getParameters() as $parameter) {
$parameterName = $parameter->getName();
$argClassName = null;
$defaultValue = null;
if (array_key_exists($parameterName, $arguments)) {
$constructArguments[$parameterName] = $arguments[$parameterName];
continue;
}