S
S
Sergey2022-04-09 09:14:36
PHP
Sergey, 2022-04-09 09:14:36

How to test handler?

Hello. How is the handler tested?
There is this one:

public function __construct(
        private CityRepository $cityRepository
    )
    {
    }

    public function __invoke(CommandInterface $command): void
    {
        $city = new City(
            Id::generate(),
            $command->getName(),
            $command->getLocation(),
            new DateTimeImmutable()       
        );
        $this->cityRepository->add($city);
    }

I want to check that the handler writes a value to the base (or should I not do this at all and should only check that the `__invoke` method somehow fires?)
public function setUp(): void
   {
       BypassFinals::enable();
       parent::setUp();
       $this->mock = $this->getMockBuilder(CreateCityHandler::class)
           ->disableOriginalConstructor()
           ->getMock();
   }
   public function testCreate() {
       $this->mock->__invoke(new CreateCityCommand(
           $name = 'Изумрудный город',
           1
       ));
   }

And the question is, what can I check? I can't check what got into the database, because I don't know the Id by which the values ​​will get there, the handler returns nothing void. How are they generally tested?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
Dmitry Gordinskiy, 2022-04-09
@DmitriyGordinskiy

If you are writing a Unit test, instead of CityRepository, use a mock that will check that exactly the object that you expect came into it.

H
HellWalk, 2022-04-09
@HellWalk

If we are not talking about pure unit tests (they are confusing), but functional testing (based on the same phpunit functionality), then:

I can't check what got into the database, because I don't know the Id by which the values ​​will get there

But you know the name of the added city - use it and check if such a city has appeared in the database.
PS
You can optimize the entities there - as I understand it, you pass the uuid and the creation date to the constructor every time, you can make traits twice , and in essence specify:
/**
 * @ORM\Entity(repositoryClass=PostRepository::class)
 * @ORM\HasLifecycleCallbacks()
 */
class Post
{
    use IdTrait;
    use CreatedAtTrait;

   // ...

In two lines, in essence, you add two fields and their automatic filling. Rid the constructor of two parameters.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question