简体   繁体   English

如何在phpunit测试中断言Flash消息的内容?

[英]How can I assert the content of Flash messages in phpunit tests?

Any idea on how i can test CakePHP controller flash message content in phpunit testing? 关于如何在phpunit测试中测试CakePHP控制器Flash消息内容的任何想法吗? I need to test this: 我需要测试一下:

if ($var == "yes") {
   //do something
} else {         
   $this->Flash->error(__('Invalid username or password, try again;));
}

According to the documentation , if you are using version 3.4.7 or later, you can use the enableRetainFlashMessages() function before issuing your get/post/whatever. 根据文档 ,如果您使用的是3.4.7或更高版本,则可以在发出get / post / what / post / whatever之前使用enableRetainFlashMessages()函数。 Then you can check for the existence of the flash message by using assertSession(). 然后,您可以使用assertSession()检查Flash消息是否存在。

Example: 例:

$this->enableRetainFlashMessages();
$this->get('call-your-public-controller-function-here');
$this->assertSession('Invalid username or password, try again', 'Flash.flash.0.message');

I stated "according to the documentation" because I'm actually using an older version right now (3.1.13) that does not include that method, so I have not personally tested the code above. 我说“根据文档”是因为我现在实际上正在使用的旧版本(3.1.13)不包含该方法,因此我没有亲自测试上述代码。

HOWEVER... I have found that, with the version I'm using, I can basically do the same thing without issuing the enableRetainFlashMessages() call. 但是,我发现,使用我使用的版本,基本上不需要发出enableRetainFlashMessages()调用就可以执行相同的操作。 By using assertSession(), I can check for the existence of the expected message using the process described above. 通过使用assertSession(),我可以使用上述过程检查预期消息的存在。 I had assumed that it would not work, but it did! 我以为它不起作用,但是可以! (That never happens...) (那永远不会发生...)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM