やりたいこと
- App\Model\MyLINEBotのreplyメソッドをスタブ化させ、trueまたはfalseを返す
- addアクション内で書き込まれたエラーログのアサーション
問題点
- テストを実行するとreplyがスタブ化されておらず通常通りに実行される
- reply内で引数をdebugすると出力される
- 一方でテスト実行後のエラー文を見ると、replyが呼び出されていない
1) App\Test\TestCase\Controller\ReceiptsControllerTest::test_200応答 Expectation failed for method name is "reply" when invoked 1 time(s). Method was expected to be called 1 times, actually called 0 times.
php
1// テスト 2public function test_200応答() 3{ 4 $data = [ 5 'key1' => 'value1', 6 'key2' => 'value2', 7 ]; 8 $mock = $this->getMockBuilder('App\Model\MyLINEBot') 9 ->onlyMethods(['reply']) 10 ->getMock(); 11 12 $mock->expects($this->once()) 13 ->method('reply') 14 ->willReturn(true); 15 16 $this->post('/receipts/add', $data); 17 $this->assertResponseOk(); 18}
php
1/** 2 * addアクション 3 * @return void 4 */ 5public function add(): void 6{ 7 $this->autoRender = false; 8 if ($this->request->is('post')) { 9 $MyLINEBot = new MyLINEBot(); 10 $events = $this->request->getData('events'); 11 12 foreach ($events as $event) { 13 // $MyLINEBot->replyをスタブ化したい 14 if (!$MyLINEBot->reply($event['message']['text'], $event['replyToken'])) { 15 error_log('Failed to reply ' . $event['message']['text']); 16 break; 17 } 18 } 19 $this->response = $this->response->withStatus(200); 20 } else { 21 $this->response = $this->response->withStatus(404); 22 } 23}
やったこと
- reply内でのdebug
- 先述の通り、引数のdebugをすると出力される
- スタブ化コードの見直し
- おそらくメソッドの理解ができていないことが原因?
あなたの回答
tips
プレビュー