如何测试广播驱动程序?

sim*_*imo 6 laravel laravel-5.1 laravel-5.2

我想知道是否有可能ShouldBroadcast在Laravel中进行测试?我的测试将触发实现的偶数ShouldBroadcast,但是,我注意到广播并未发生。

当然,广播事件本身就是在应用程序中进行的。

有没有人尝试过这种测试?

小智 6

这是一个古老的问题,但以防万一它可以帮助某人:我为自己做了一个断言函数,应该将其添加到TestCase.php中。

想法是将广播驱动程序设置为“ log”,然后从末尾读取第4行以查看它是否是广播日志。

在你的phpunit.xml中

将以下行添加到节点:

<env name="BROADCAST_DRIVER" value="log"/>
Run Code Online (Sandbox Code Playgroud)

在您的TestCase.php文件中

添加以下功能:

public function assertEventIsBroadcasted($eventClassName, $channel=""){
  $logfileFullpath = storage_path("logs/laravel.log");
  $logfile = explode("\n", file_get_contents($logfileFullpath));

  if(count($logfile) > 4){
    $supposedLastEventLogged = $logfile[count($logfile)-5];

    $this->assertContains("Broadcasting [", $supposedLastEventLogged, "No broadcast were found.\n");

    $this->assertContains("Broadcasting [".$eventClassName."]", $supposedLastEventLogged, "A broadcast was found, but not for the classname '".$eventClassName."'.\n");

    if($channel != "")
      $this->assertContains("Broadcasting [".$eventClassName."] on channels [".$channel."]", $supposedLastEventLogged, "The expected broadcast (".$eventClassName.") event was found, but not on the expected channel '".$channel."'.\n");
  }else{
    $this->fail("No informations found in the file log '".$logfileFullpath."'.");
  }
}
Run Code Online (Sandbox Code Playgroud)