Невозможно проверить, что событие имеет свойства с Laravel 5 и PHPUnit

Я пытаюсь проверить, что мои события получают правильные свойства при запуске. Я могу определить, что событие было запущено, но не то, что были отправлены правильные свойства.

PHP

<?php

use App\Events\ManifestRecordCreated;
use App\ManifestFile;
use Illuminate\Support\Facades\Event;
use Illuminate\Support\Facades\Storage;

class ManifestTest extends TestCase {

    /**
     * This is the test I'd like to perfom.
     */
    public function testOhLookMyEventGetsTheRightProperties()
    {
      Event::shouldReceive('fire')->once()->withArgs(array('App\\Events\\ManifestRecordCreated', array (
         'poseId' => 2,
         'stateId' => 1,
         'manifestId' => 1,
         )
      ));
      Event::fire(new ManifestRecordCreated(2, 1, 1));
    }
    /**
     * Test that the event is fired.
     */
    public function testOnlyOneThatWorks()
    {
       Event::shouldReceive('fire')->once()->with(Mockery::any());
       Event::fire(new ManifestRecordCreated(2, 1, 1));
    }

    /**
     * I'd like to test if the evnt is getting the right arguments.
     */
    public function testGraspingAtStraws()
    {
      $args = array ('App\Events\ManifestRecordCreated' => array (
        'class' => 'App\Events\ManifestRecordCreated',
        'properties' => array (
         'poseId' => 2,
         'stateId' => 1,
         'manifestId' => 1,
         ),
        'getters' => array (),
        ),
      );
      Event::shouldReceive('fire')->once()->withArgs($args);
      Event::fire(new ManifestRecordCreated(2, 1, 1));
    }
    /**
     * I don't think I need this, but I did read it somewhere in my search.
     */
    public function tearDown()
    {
        \Mockery::close();
    }
}

Результаты тестирования PHPUnit

1) ManifestTest::testOhLookMyEventGetsTheRightProperties
Mockery\Exception\NoMatchingExpectationException: No matching handler found for Mockery_0_Illuminate_Events_Dispatcher::fire(object(App\Events\ManifestRecordCreated)). Either the method was unexpected or its arguments matched no expected argument list for this method

Objects: ( array (
  'App\\Events\\ManifestRecordCreated' => 
  array (
    'class' => 'App\\Events\\ManifestRecordCreated',
    'properties' => 
    array (
      'poseId' => 2,
      'stateId' => 1,
      'manifestId' => 1,
    ),
    'getters' => 
    array (
    ),
  ),
))

2) ManifestTest::testGraspingAtStraws
ErrorException: Undefined offset: 0

документация Laravel 5 не очень полезна.

Этот подход игнорирует все, кроме события.


person whoacowboy    schedule 23.04.2015    source источник


Ответы (1)


Проблема ErrorException: Undefined offset: 0 заключается в том, что массив передается с именованными ключами, а не в виде списка от 0 до X параметров, которые вы ожидаете передать. (В качестве имени ключа используется 'App\\Events\\ManifestRecordCreated')

Обычно вы просто передаете список, но с параметрами объекта сопоставление может завершиться ошибкой, потому что это не один и тот же экземпляр, поэтому вы можете использовать метод hamcrest equalTo для сравнения значения объекта, а не экземпляра

Что-то типа

public function testObjectValuesEqual()
{
  Event::shouldReceive('fire')->once()->withArgs([Matchers::equalTo(new ManifestRecordCreated(2, 1, 1))]);
  Event::fire(new ManifestRecordCreated(2, 1, 1));
}
person Rich    schedule 07.01.2019