I have a bunch of handlers. Every of them, eventually, contains code for saving data and releasing events.
How to test CommandHandler
? What should be tested? For now it is unit tests, maybe it should be integrational? Should I mock anything or not? Why? Should it be tested at all?
Code of handlers:
public function __invoke(AddCategory $command): int
{
// some code
$this->categories->save($category);
$this->events->publishAll($category->releaseEvents());
return $category->id()->value;
}
public function __invoke(RenameCategory $command): void
{
// some code
$this->categories->save($category);
$this->events->publishAll($category->releaseEvents());
}
At the moment my tests look like that:
Test addition
protected function setUp(): void
{
$this->categories = new TestCategoryRepository();
$this->events = new TestEventDispatcher();
$this->handler = new AddCategoryHandler($this->categories, $this->events);
}
public function testHandler(): void
{
// preparing code
($this->handler)($command);
$this->assertTrue($currentEventsCountMoreThanInitialEventsCount);
$this->assertTrue($currentRepositoryCountMoreThanInitialRepositoryCount);
$this->assertIsInt($categoryId);
$this->assertNotNull($category);
}
Test some changes:
protected function setUp(): void
{
$this->categories = $this->createMock(CategoryRepository::class);
$this->events = new TestEventDispatcher();
$this->handler = new RenameCategoryHandler($this->categories, $this->events);
}
public function testHandler(): void
{
// preparing code
$this->categories->expects($this->once())
->method('getById')
->with($categoryId)
->willReturn($category);
$this->categories->expects($this->once())->method('save');
($this->handler)($command);
$this->assertTrue($currentEventsCountMoreThanInitialEventsCount);
}