Files
Mangarr/tests/Domain/Scraping/Application/CommandHandler/ScrapeChapterHandlerTest.php
2025-02-07 11:56:51 +01:00

83 lines
2.9 KiB
PHP

<?php
namespace App\Tests\Domain\Scraping\Application\CommandHandler;
use App\Domain\Scraping\Application\Command\ScrapeChapter;
use App\Domain\Scraping\Application\CommandHandler\ScrapeChapterHandler;
use App\Domain\Scraping\Domain\Event\ChapterScrapingFailed;
use App\Domain\Scraping\Domain\Event\ChapterScrapingStarted;
use App\Tests\Domain\Scraping\Adapter\InMemoryEventBus;
use App\Tests\Domain\Scraping\Adapter\InMemoryScraperAdapter;
use App\Tests\Domain\Scraping\Adapter\InMemoryScrapingJobRepository;
use PHPUnit\Framework\TestCase;
class ScrapeChapterHandlerTest extends TestCase
{
private InMemoryScraperAdapter $scraper;
private InMemoryScrapingJobRepository $repository;
private InMemoryEventBus $eventBus;
private ScrapeChapterHandler $handler;
protected function setUp(): void
{
$this->scraper = new InMemoryScraperAdapter();
$this->repository = new InMemoryScrapingJobRepository();
$this->eventBus = new InMemoryEventBus();
$this->handler = new ScrapeChapterHandler(
$this->scraper,
$this->repository,
$this->eventBus
);
}
public function testHandleSuccessfully(): void
{
$command = new ScrapeChapter(
mangaId: 1,
chapterNumber: 2,
sourceId: 3,
);
$this->handler->handle($command);
$scrapingJobs = $this->repository->getJobs();
$this->assertCount(1, $scrapingJobs);
$job = $scrapingJobs[0];
$savedJobs = $this->repository->getJobs();
$this->assertCount(1, $savedJobs);
$this->assertSame($job, $savedJobs[0]);
$dispatchedMessages = $this->eventBus->getDispatchedMessages();
$this->assertCount(1, $dispatchedMessages);
$this->assertInstanceOf(ChapterScrapingStarted::class, $dispatchedMessages[0]);
$this->assertEquals($job->getId(), $dispatchedMessages[0]->getJobId());
}
public function testHandleThrowsException(): void
{
$command = new ScrapeChapter(
mangaId: 1,
chapterNumber: 2,
sourceId: 3,
);
$exception = new \Exception('Scraping failed');
$this->scraper->simulateError($exception);
$this->expectException(\Exception::class);
$this->expectExceptionMessage('Scraping failed');
try {
$this->handler->handle($command);
} finally {
$dispatchedMessages = $this->eventBus->getDispatchedMessages();
$this->assertCount(2, $dispatchedMessages);
$this->assertInstanceOf(ChapterScrapingStarted::class, $dispatchedMessages[0]);
$this->assertInstanceOf(ChapterScrapingFailed::class, $dispatchedMessages[1]);
$this->assertEquals(2, $dispatchedMessages[1]->getChapterNumber());
$this->assertEquals('Scraping failed', $dispatchedMessages[1]->getReason());
}
}
}