Fix notices reported by latest PHPUnit version

This commit is contained in:
Alejandro Celaya
2025-12-15 14:17:36 +01:00
parent 2c8bc6aca0
commit da53c5a206
51 changed files with 174 additions and 149 deletions

View File

@@ -15,7 +15,6 @@ use Shlinkio\Shlink\Core\Config\Options\UrlShortenerOptions;
use Shlinkio\Shlink\Core\Domain\DomainServiceInterface;
use Shlinkio\Shlink\Core\Domain\Entity\Domain;
use Shlinkio\Shlink\Rest\ApiKey\Model\RoleDefinition;
use Symfony\Component\Console\Input\InputInterface;
class RoleResolverTest extends TestCase
{
@@ -46,17 +45,6 @@ class RoleResolverTest extends TestCase
public static function provideRoles(): iterable
{
$domain = self::domainWithId(Domain::withAuthority('example.com'));
$buildInput = static fn (array $definition) => function (TestCase $test) use ($definition): InputInterface {
$returnMap = [];
foreach ($definition as $param => $returnValue) {
$returnMap[] = [$param, $returnValue];
}
$input = $test->createStub(InputInterface::class);
$input->method('getOption')->willReturnMap($returnMap);
return $input;
};
yield 'no roles' => [
new ApiKeyInput(),
@@ -107,6 +95,8 @@ class RoleResolverTest extends TestCase
$input = new ApiKeyInput();
$input->domain = 'default.com';
$this->domainService->expects($this->never())->method('getOrCreate');
$this->expectException(InvalidRoleConfigException::class);
[...$this->resolver->determineRoles($input)];

View File

@@ -25,7 +25,7 @@ class GenerateKeyCommandTest extends TestCase
protected function setUp(): void
{
$this->apiKeyService = $this->createMock(ApiKeyServiceInterface::class);
$roleResolver = $this->createMock(RoleResolverInterface::class);
$roleResolver = $this->createStub(RoleResolverInterface::class);
$roleResolver->method('determineRoles')->willReturn([]);
$command = new GenerateKeyCommand($this->apiKeyService, $roleResolver);

View File

@@ -16,6 +16,7 @@ use Exception;
use PHPUnit\Framework\Attributes\DataProvider;
use PHPUnit\Framework\Attributes\Test;
use PHPUnit\Framework\MockObject\MockObject;
use PHPUnit\Framework\MockObject\Stub;
use PHPUnit\Framework\TestCase;
use Shlinkio\Shlink\CLI\Command\Db\CreateDatabaseCommand;
use Shlinkio\Shlink\CLI\Util\ProcessRunnerInterface;
@@ -31,19 +32,19 @@ class CreateDatabaseCommandTest extends TestCase
private CommandTester $commandTester;
private MockObject & ProcessRunnerInterface $processHelper;
private MockObject & Connection $regularConn;
private MockObject & ClassMetadataFactory $metadataFactory;
private Stub & ClassMetadataFactory $metadataFactory;
/** @var MockObject&AbstractSchemaManager<SQLitePlatform> */
private MockObject & AbstractSchemaManager $schemaManager;
private MockObject & Driver $driver;
private Stub & Driver $driver;
protected function setUp(): void
{
$locker = $this->createMock(LockFactory::class);
$lock = $this->createMock(SharedLockInterface::class);
$locker = $this->createStub(LockFactory::class);
$lock = $this->createStub(SharedLockInterface::class);
$lock->method('acquire')->willReturn(true);
$locker->method('createLock')->willReturn($lock);
$phpExecutableFinder = $this->createMock(PhpExecutableFinder::class);
$phpExecutableFinder = $this->createStub(PhpExecutableFinder::class);
$phpExecutableFinder->method('find')->willReturn('/usr/local/bin/php');
$this->processHelper = $this->createMock(ProcessRunnerInterface::class);
@@ -51,15 +52,15 @@ class CreateDatabaseCommandTest extends TestCase
$this->regularConn = $this->createMock(Connection::class);
$this->regularConn->method('createSchemaManager')->willReturn($this->schemaManager);
$this->driver = $this->createMock(Driver::class);
$this->driver = $this->createStub(Driver::class);
$this->regularConn->method('getDriver')->willReturn($this->driver);
$this->metadataFactory = $this->createMock(ClassMetadataFactory::class);
$em = $this->createMock(EntityManagerInterface::class);
$this->metadataFactory = $this->createStub(ClassMetadataFactory::class);
$em = $this->createStub(EntityManagerInterface::class);
$em->method('getConnection')->willReturn($this->regularConn);
$em->method('getMetadataFactory')->willReturn($this->metadataFactory);
$noDbNameConn = $this->createMock(Connection::class);
$noDbNameConn = $this->createStub(Connection::class);
$noDbNameConn->method('createSchemaManager')->willReturn($this->schemaManager);
$command = new CreateDatabaseCommand($locker, $this->processHelper, $phpExecutableFinder, $em, $noDbNameConn);
@@ -70,13 +71,13 @@ class CreateDatabaseCommandTest extends TestCase
public function successMessageIsPrintedIfDatabaseAlreadyExists(): void
{
$this->regularConn->expects($this->never())->method('getParams');
$this->driver->method('getDatabasePlatform')->willReturn($this->createMock(AbstractPlatform::class));
$metadataMock = $this->createMock(ClassMetadata::class);
$metadataMock->expects($this->once())->method('getTableName')->willReturn('foo_table');
$this->metadataFactory->method('getAllMetadata')->willReturn([$metadataMock]);
$this->schemaManager->expects($this->never())->method('createDatabase');
$this->schemaManager->expects($this->once())->method('listTableNames')->willReturn(['foo_table', 'bar_table']);
$this->processHelper->expects($this->never())->method('run');
$this->commandTester->execute([]);
$output = $this->commandTester->getDisplay();
@@ -87,13 +88,14 @@ class CreateDatabaseCommandTest extends TestCase
#[Test]
public function databaseIsCreatedIfItDoesNotExist(): void
{
$this->driver->method('getDatabasePlatform')->willReturn($this->createMock(AbstractPlatform::class));
$this->driver->method('getDatabasePlatform')->willReturn($this->createStub(AbstractPlatform::class));
$shlinkDatabase = 'shlink_database';
$this->regularConn->expects($this->once())->method('getParams')->willReturn(['dbname' => $shlinkDatabase]);
$this->metadataFactory->method('getAllMetadata')->willReturn([]);
$this->schemaManager->expects($this->once())->method('createDatabase')->with($shlinkDatabase);
$this->schemaManager->expects($this->once())->method('listTableNames')->willThrowException(new Exception(''));
$this->processHelper->expects($this->once())->method('run');
$this->commandTester->execute([]);
}
@@ -102,9 +104,9 @@ class CreateDatabaseCommandTest extends TestCase
public function tablesAreCreatedIfDatabaseIsEmpty(array $tables): void
{
$this->regularConn->expects($this->never())->method('getParams');
$this->driver->method('getDatabasePlatform')->willReturn($this->createMock(AbstractPlatform::class));
$this->driver->method('getDatabasePlatform')->willReturn($this->createStub(AbstractPlatform::class));
$metadata = $this->createMock(ClassMetadata::class);
$metadata = $this->createStub(ClassMetadata::class);
$metadata->method('getTableName')->willReturn('shlink_table');
$this->metadataFactory->method('getAllMetadata')->willReturn([$metadata]);
$this->schemaManager->expects($this->never())->method('createDatabase');

View File

@@ -23,12 +23,12 @@ class MigrateDatabaseCommandTest extends TestCase
protected function setUp(): void
{
$locker = $this->createMock(LockFactory::class);
$lock = $this->createMock(SharedLockInterface::class);
$locker = $this->createStub(LockFactory::class);
$lock = $this->createStub(SharedLockInterface::class);
$lock->method('acquire')->willReturn(true);
$locker->method('createLock')->willReturn($lock);
$phpExecutableFinder = $this->createMock(PhpExecutableFinder::class);
$phpExecutableFinder = $this->createStub(PhpExecutableFinder::class);
$phpExecutableFinder->method('find')->willReturn('/usr/local/bin/php');
$this->processHelper = $this->createMock(ProcessRunnerInterface::class);

View File

@@ -3,6 +3,7 @@
namespace ShlinkioTest\Shlink\CLI\Command\Integration;
use Exception;
use PHPUnit\Framework\Attributes\AllowMockObjectsWithoutExpectations;
use PHPUnit\Framework\Attributes\Test;
use PHPUnit\Framework\Attributes\TestWith;
use PHPUnit\Framework\MockObject\MockObject;
@@ -27,6 +28,8 @@ class MatomoSendVisitsCommandTest extends TestCase
#[Test]
public function warningDisplayedIfIntegrationIsNotEnabled(): void
{
$this->visitSender->expects($this->never())->method('sendVisitsInDateRange');
[$output, $exitCode] = $this->executeCommand(matomoEnabled: false);
self::assertStringContainsString('Matomo integration is not enabled in this Shlink instance', $output);
@@ -38,7 +41,7 @@ class MatomoSendVisitsCommandTest extends TestCase
#[TestWith([false], 'not interactive')]
public function warningIsOnlyDisplayedInInteractiveMode(bool $interactive): void
{
$this->visitSender->method('sendVisitsInDateRange')->willReturn(new SendVisitsResult());
$this->visitSender->expects($this->once())->method('sendVisitsInDateRange')->willReturn(new SendVisitsResult());
[$output] = $this->executeCommand(['y'], ['interactive' => $interactive]);
@@ -80,7 +83,7 @@ class MatomoSendVisitsCommandTest extends TestCase
#[Test]
public function printsResultOfSendingVisits(): void
{
$this->visitSender->method('sendVisitsInDateRange')->willReturnCallback(
$this->visitSender->expects($this->once())->method('sendVisitsInDateRange')->willReturnCallback(
function (DateRange $_, MatomoSendVisitsCommand $command): SendVisitsResult {
// Call it a few times for an easier match of its result in the command putput
$command->success(0);
@@ -99,7 +102,7 @@ class MatomoSendVisitsCommandTest extends TestCase
self::assertStringContainsString('...E.E', $output);
}
#[Test]
#[Test, AllowMockObjectsWithoutExpectations]
#[TestWith([[], 'All time'])]
#[TestWith([['--since' => '2023-05-01'], 'Since 2023-05-01 00:00:00'])]
#[TestWith([['--until' => '2023-05-01'], 'Until 2023-05-01 00:00:00'])]

View File

@@ -9,6 +9,7 @@ use PHPUnit\Framework\Assert;
use PHPUnit\Framework\Attributes\DataProvider;
use PHPUnit\Framework\Attributes\Test;
use PHPUnit\Framework\MockObject\MockObject;
use PHPUnit\Framework\MockObject\Stub;
use PHPUnit\Framework\TestCase;
use Shlinkio\Shlink\CLI\Command\ShortUrl\CreateShortUrlCommand;
use Shlinkio\Shlink\Core\Config\Options\UrlShortenerOptions;
@@ -27,12 +28,12 @@ class CreateShortUrlCommandTest extends TestCase
{
private CommandTester $commandTester;
private MockObject & UrlShortenerInterface $urlShortener;
private MockObject & ShortUrlStringifierInterface $stringifier;
private Stub & ShortUrlStringifierInterface $stringifier;
protected function setUp(): void
{
$this->urlShortener = $this->createMock(UrlShortenerInterface::class);
$this->stringifier = $this->createMock(ShortUrlStringifierInterface::class);
$this->stringifier = $this->createStub(ShortUrlStringifierInterface::class);
$command = new CreateShortUrlCommand(
$this->urlShortener,
@@ -49,9 +50,7 @@ class CreateShortUrlCommandTest extends TestCase
$this->urlShortener->expects($this->once())->method('shorten')->withAnyParameters()->willReturn(
UrlShorteningResult::withoutErrorOnEventDispatching($shortUrl),
);
$this->stringifier->expects($this->once())->method('stringify')->with($shortUrl)->willReturn(
'stringified_short_url',
);
$this->stringifier->method('stringify')->with($shortUrl)->willReturn('stringified_short_url');
$this->commandTester->execute([
'long-url' => 'http://domain.com/foo/bar',
@@ -71,9 +70,7 @@ class CreateShortUrlCommandTest extends TestCase
$this->urlShortener->expects($this->once())->method('shorten')->withAnyParameters()->willReturn(
UrlShorteningResult::withoutErrorOnEventDispatching($shortUrl),
);
$this->stringifier->expects($this->once())->method('stringify')->with($shortUrl)->willReturn(
'stringified_short_url',
);
$this->stringifier->method('stringify')->with($shortUrl)->willReturn('stringified_short_url');
$this->commandTester->setInputs([$shortUrl->getLongUrl()]);
$this->commandTester->execute([]);
@@ -104,9 +101,7 @@ class CreateShortUrlCommandTest extends TestCase
return true;
}),
)->willReturn(UrlShorteningResult::withoutErrorOnEventDispatching($shortUrl));
$this->stringifier->expects($this->once())->method('stringify')->with($shortUrl)->willReturn(
'stringified_short_url',
);
$this->stringifier->method('stringify')->with($shortUrl)->willReturn('stringified_short_url');
$this->commandTester->execute([
'long-url' => 'http://domain.com/foo/bar',

View File

@@ -26,6 +26,8 @@ class DeleteTagsCommandTest extends TestCase
#[Test]
public function errorIsReturnedWhenNoTagsAreProvided(): void
{
$this->tagService->expects($this->never())->method('deleteTags');
$this->commandTester->execute([]);
$output = $this->commandTester->getDisplay();

View File

@@ -4,9 +4,11 @@ declare(strict_types=1);
namespace ShlinkioTest\Shlink\CLI\Command\Visit;
use PHPUnit\Framework\Attributes\AllowMockObjectsWithoutExpectations;
use PHPUnit\Framework\Attributes\DataProvider;
use PHPUnit\Framework\Attributes\Test;
use PHPUnit\Framework\MockObject\MockObject;
use PHPUnit\Framework\MockObject\Stub;
use PHPUnit\Framework\TestCase;
use Shlinkio\Shlink\CLI\Command\Visit\DownloadGeoLiteDbCommand;
use Shlinkio\Shlink\CLI\Command\Visit\LocateVisitsCommand;
@@ -31,26 +33,27 @@ use function sprintf;
use const PHP_EOL;
#[AllowMockObjectsWithoutExpectations]
class LocateVisitsCommandTest extends TestCase
{
private CommandTester $commandTester;
private MockObject & VisitLocatorInterface $visitService;
private MockObject & VisitToLocationHelperInterface $visitToLocation;
private MockObject & Lock\LockInterface $lock;
private MockObject & Command $downloadDbCommand;
private Stub & Lock\LockInterface $lock;
private Stub & Command $downloadDbCommand;
protected function setUp(): void
{
$this->visitService = $this->createMock(VisitLocatorInterface::class);
$this->visitToLocation = $this->createMock(VisitToLocationHelperInterface::class);
$locker = $this->createMock(Lock\LockFactory::class);
$this->lock = $this->createMock(Lock\SharedLockInterface::class);
$locker = $this->createStub(Lock\LockFactory::class);
$this->lock = $this->createStub(Lock\SharedLockInterface::class);
$locker->method('createLock')->willReturn($this->lock);
$command = new LocateVisitsCommand($this->visitService, $this->visitToLocation, $locker);
$this->downloadDbCommand = CliTestUtils::createCommandMock(DownloadGeoLiteDbCommand::NAME);
$this->downloadDbCommand = CliTestUtils::createCommandStub(DownloadGeoLiteDbCommand::NAME);
$this->commandTester = CliTestUtils::testerForCommand($command, $this->downloadDbCommand);
}

View File

@@ -30,8 +30,8 @@ class ApplicationFactoryTest extends TestCase
'baz' => 'baz',
],
]);
$sm->setService('foo', CliTestUtils::createCommandMock('foo'));
$sm->setService('bar', CliTestUtils::createCommandMock('bar'));
$sm->setService('foo', CliTestUtils::createCommandStub('foo'));
$sm->setService('bar', CliTestUtils::createCommandStub('bar'));
$instance = ($this->factory)($sm);

View File

@@ -26,6 +26,7 @@ class InputUtilsTest extends TestCase
#[TestWith([''], 'empty string')]
public function processDateReturnsNullForEmptyDates(string|null $date): void
{
$this->input->expects($this->never())->method('writeln');
self::assertNull(InputUtils::processDate('name', $date, $this->input));
}
@@ -33,6 +34,7 @@ class InputUtilsTest extends TestCase
public function processDateReturnsAtomFormatedForValidDates(): void
{
$date = '2025-01-20';
$this->input->expects($this->never())->method('writeln');
self::assertEquals(Chronos::parse($date)->toAtomString(), InputUtils::processDate('name', $date, $this->input));
}

View File

@@ -5,6 +5,7 @@ declare(strict_types=1);
namespace ShlinkioTest\Shlink\CLI\RedirectRule;
use Doctrine\Common\Collections\ArrayCollection;
use PHPUnit\Framework\Attributes\AllowMockObjectsWithoutExpectations;
use PHPUnit\Framework\Attributes\DataProvider;
use PHPUnit\Framework\Attributes\Test;
use PHPUnit\Framework\MockObject\MockObject;
@@ -20,6 +21,7 @@ use Symfony\Component\Console\Style\StyleInterface;
use function sprintf;
#[AllowMockObjectsWithoutExpectations]
class RedirectRuleHandlerTest extends TestCase
{
private RedirectRuleHandler $handler;

View File

@@ -6,7 +6,7 @@ namespace ShlinkioTest\Shlink\CLI\Util;
use PHPUnit\Framework\Assert;
use PHPUnit\Framework\MockObject\Generator\Generator;
use PHPUnit\Framework\MockObject\MockObject;
use PHPUnit\Framework\MockObject\Stub;
use Symfony\Component\Console\Application;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputDefinition;
@@ -14,7 +14,7 @@ use Symfony\Component\Console\Tester\CommandTester;
class CliTestUtils
{
public static function createCommandMock(string $name): MockObject & Command
public static function createCommandStub(string $name): Stub & Command
{
static $generator = null;
@@ -24,7 +24,7 @@ class CliTestUtils
$command = $generator->testDouble(
Command::class,
mockObject: true,
mockObject: false,
callOriginalConstructor: false,
callOriginalClone: false,
);

View File

@@ -26,7 +26,7 @@ class ProcessRunnerTest extends TestCase
{
$this->helper = $this->createMock(ProcessHelper::class);
$this->formatter = $this->createMock(DebugFormatterHelper::class);
$helperSet = $this->createMock(HelperSet::class);
$helperSet = $this->createStub(HelperSet::class);
$helperSet->method('get')->willReturn($this->formatter);
$this->helper->method('getHelperSet')->willReturn($helperSet);
$this->process = $this->createMock(Process::class);

View File

@@ -5,7 +5,6 @@ declare(strict_types=1);
namespace ShlinkioTest\Shlink\CLI\Util;
use PHPUnit\Framework\Attributes\Test;
use PHPUnit\Framework\MockObject\MockObject;
use PHPUnit\Framework\TestCase;
use ReflectionObject;
use Shlinkio\Shlink\CLI\Util\ShlinkTable;
@@ -15,15 +14,6 @@ use Symfony\Component\Console\Output\OutputInterface;
class ShlinkTableTest extends TestCase
{
private ShlinkTable $shlinkTable;
private MockObject & Table $baseTable;
protected function setUp(): void
{
$this->baseTable = $this->createMock(Table::class);
$this->shlinkTable = ShlinkTable::fromBaseTable($this->baseTable);
}
#[Test]
public function renderMakesTableToBeRenderedWithProvidedInfo(): void
{
@@ -32,22 +22,23 @@ class ShlinkTableTest extends TestCase
$headerTitle = 'Header';
$footerTitle = 'Footer';
$this->baseTable->expects($this->once())->method('setStyle')->with(
$baseTable = $this->createMock(Table::class);
$baseTable->expects($this->once())->method('setStyle')->with(
$this->isInstanceOf(TableStyle::class),
)->willReturnSelf();
$this->baseTable->expects($this->once())->method('setHeaders')->with($headers)->willReturnSelf();
$this->baseTable->expects($this->once())->method('setRows')->with($rows)->willReturnSelf();
$this->baseTable->expects($this->once())->method('setFooterTitle')->with($footerTitle)->willReturnSelf();
$this->baseTable->expects($this->once())->method('setHeaderTitle')->with($headerTitle)->willReturnSelf();
$this->baseTable->expects($this->once())->method('render')->with()->willReturnSelf();
$baseTable->expects($this->once())->method('setHeaders')->with($headers)->willReturnSelf();
$baseTable->expects($this->once())->method('setRows')->with($rows)->willReturnSelf();
$baseTable->expects($this->once())->method('setFooterTitle')->with($footerTitle)->willReturnSelf();
$baseTable->expects($this->once())->method('setHeaderTitle')->with($headerTitle)->willReturnSelf();
$baseTable->expects($this->once())->method('render')->with()->willReturnSelf();
$this->shlinkTable->render($headers, $rows, $footerTitle, $headerTitle);
ShlinkTable::fromBaseTable($baseTable)->render($headers, $rows, $footerTitle, $headerTitle);
}
#[Test]
public function newTableIsCreatedForFactoryMethod(): void
{
$instance = ShlinkTable::default($this->createMock(OutputInterface::class));
$instance = ShlinkTable::default($this->createStub(OutputInterface::class));
$ref = new ReflectionObject($instance);
$baseTable = $ref->getProperty('baseTable');

View File

@@ -47,7 +47,7 @@ class PixelActionTest extends TestCase
$request->withAttribute(REDIRECT_URL_REQUEST_ATTRIBUTE, null),
);
$response = $this->action->process($request, $this->createMock(RequestHandlerInterface::class));
$response = $this->action->process($request, $this->createStub(RequestHandlerInterface::class));
self::assertInstanceOf(PixelResponse::class, $response);
self::assertEquals(200, $response->getStatusCode());

View File

@@ -36,7 +36,7 @@ class RedirectActionTest extends TestCase
$this->requestTracker = $this->createMock(RequestTrackerInterface::class);
$this->redirectRespHelper = $this->createMock(RedirectResponseHelperInterface::class);
$redirectBuilder = $this->createMock(ShortUrlRedirectionBuilderInterface::class);
$redirectBuilder = $this->createStub(ShortUrlRedirectionBuilderInterface::class);
$redirectBuilder->method('buildShortUrlRedirect')->willReturn(self::LONG_URL);
$this->action = new RedirectAction(
@@ -66,7 +66,7 @@ class RedirectActionTest extends TestCase
self::LONG_URL,
)->willReturn($expectedResp);
$response = $this->action->process($request, $this->createMock(RequestHandlerInterface::class));
$response = $this->action->process($request, $this->createStub(RequestHandlerInterface::class));
self::assertSame($expectedResp, $response);
}
@@ -79,11 +79,12 @@ class RedirectActionTest extends TestCase
ShortUrlIdentifier::fromShortCodeAndDomain($shortCode, ''),
)->willThrowException(ShortUrlNotFoundException::fromNotFound(ShortUrlIdentifier::fromShortCodeAndDomain('')));
$this->requestTracker->expects($this->never())->method('trackIfApplicable');
$this->redirectRespHelper->expects($this->never())->method('buildRedirectResponse');
$handler = $this->createMock(RequestHandlerInterface::class);
$handler->expects($this->once())->method('handle')->withAnyParameters()->willReturn(new Response());
$request = (new ServerRequest())->withAttribute('shortCode', $shortCode);
$request = new ServerRequest()->withAttribute('shortCode', $shortCode);
$this->action->process($request, $handler);
}
}

View File

@@ -9,6 +9,7 @@ use Laminas\Diactoros\ServerRequestFactory;
use Laminas\Diactoros\Uri;
use Mezzio\Router\Route;
use Mezzio\Router\RouteResult;
use PHPUnit\Framework\Attributes\AllowMockObjectsWithoutExpectations;
use PHPUnit\Framework\Attributes\DataProvider;
use PHPUnit\Framework\Attributes\Test;
use PHPUnit\Framework\MockObject\MockObject;
@@ -24,6 +25,7 @@ use Shlinkio\Shlink\Core\Util\RedirectResponseHelperInterface;
use function Laminas\Stratigility\middleware;
#[AllowMockObjectsWithoutExpectations]
class NotFoundRedirectResolverTest extends TestCase
{
private NotFoundRedirectResolver $resolver;

View File

@@ -5,9 +5,11 @@ declare(strict_types=1);
namespace ShlinkioTest\Shlink\Core\Domain;
use Doctrine\ORM\EntityManagerInterface;
use PHPUnit\Framework\Attributes\AllowMockObjectsWithoutExpectations;
use PHPUnit\Framework\Attributes\DataProvider;
use PHPUnit\Framework\Attributes\Test;
use PHPUnit\Framework\MockObject\MockObject;
use PHPUnit\Framework\MockObject\Stub;
use PHPUnit\Framework\TestCase;
use Shlinkio\Shlink\Core\Config\EmptyNotFoundRedirectConfig;
use Shlinkio\Shlink\Core\Config\NotFoundRedirects;
@@ -24,12 +26,12 @@ use Shlinkio\Shlink\Rest\Entity\ApiKey;
class DomainServiceTest extends TestCase
{
private DomainService $domainService;
private MockObject & EntityManagerInterface $em;
private Stub & EntityManagerInterface $em;
private MockObject & DomainRepositoryInterface $repo;
protected function setUp(): void
{
$this->em = $this->createMock(EntityManagerInterface::class);
$this->em = $this->createStub(EntityManagerInterface::class);
$this->repo = $this->createMock(DomainRepositoryInterface::class);
$this->domainService = new DomainService(
$this->em,
@@ -106,21 +108,21 @@ class DomainServiceTest extends TestCase
];
}
#[Test]
#[Test, AllowMockObjectsWithoutExpectations]
public function getDomainThrowsExceptionWhenDomainIsNotFound(): void
{
$this->em->expects($this->once())->method('find')->with(Domain::class, '123')->willReturn(null);
$this->em->method('find')->with(Domain::class, '123')->willReturn(null);
$this->expectException(DomainNotFoundException::class);
$this->domainService->getDomain('123');
}
#[Test]
#[Test, AllowMockObjectsWithoutExpectations]
public function getDomainReturnsEntityWhenFound(): void
{
$domain = Domain::withAuthority('');
$this->em->expects($this->once())->method('find')->with(Domain::class, '123')->willReturn($domain);
$this->em->method('find')->with(Domain::class, '123')->willReturn($domain);
$result = $this->domainService->getDomain('123');
@@ -134,8 +136,7 @@ class DomainServiceTest extends TestCase
$this->repo->expects($this->once())->method('findOneByAuthority')->with($authority, $apiKey)->willReturn(
$foundDomain,
);
$this->em->expects($this->once())->method('persist')->with($foundDomain ?? $this->isInstanceOf(Domain::class));
$this->em->expects($this->once())->method('flush');
$this->em->method('persist')->with($foundDomain ?? $this->isInstanceOf(Domain::class));
$result = $this->domainService->getOrCreate($authority, $apiKey);
@@ -152,8 +153,6 @@ class DomainServiceTest extends TestCase
$domain->setId('1');
$apiKey = ApiKey::fromMeta(ApiKeyMeta::withRoles(RoleDefinition::forDomain($domain)));
$this->repo->expects($this->once())->method('findOneByAuthority')->with($authority, $apiKey)->willReturn(null);
$this->em->expects($this->never())->method('persist');
$this->em->expects($this->never())->method('flush');
$this->expectException(DomainNotFoundException::class);
@@ -169,8 +168,7 @@ class DomainServiceTest extends TestCase
$this->repo->expects($this->once())->method('findOneByAuthority')->with($authority, $apiKey)->willReturn(
$foundDomain,
);
$this->em->expects($this->once())->method('persist')->with($foundDomain ?? $this->isInstanceOf(Domain::class));
$this->em->expects($this->once())->method('flush');
$this->em->method('persist')->with($foundDomain ?? $this->isInstanceOf(Domain::class));
$result = $this->domainService->configureNotFoundRedirects($authority, NotFoundRedirects::withRedirects(
'foo.com',

View File

@@ -42,7 +42,7 @@ class NotFoundRedirectHandlerTest extends TestCase
$this->next = $this->createMock(RequestHandlerInterface::class);
$this->req = ServerRequestFactory::fromGlobals()->withAttribute(
NotFoundType::class,
$this->createMock(NotFoundType::class),
$this->createStub(NotFoundType::class),
);
}

View File

@@ -33,7 +33,7 @@ class NotFoundTrackerMiddlewareTest extends TestCase
$this->request = ServerRequestFactory::fromGlobals()->withAttribute(
NotFoundType::class,
$this->createMock(NotFoundType::class),
$this->createStub(NotFoundType::class),
);
}

View File

@@ -34,7 +34,7 @@ class CloseDbConnectionEventListenerDelegatorTest extends TestCase
};
$this->container->expects($this->once())->method('get')->with('em')->willReturn(
$this->createMock(ReopeningEntityManagerInterface::class),
$this->createStub(ReopeningEntityManagerInterface::class),
);
($this->delegator)($this->container, '', $callback);

View File

@@ -29,7 +29,7 @@ class RequestIdProviderTest extends TestCase
$initialId = $this->middleware->currentRequestId();
self::assertEquals($initialId, $this->provider->currentRequestId());
$handler = $this->createMock(RequestHandlerInterface::class);
$handler = $this->createStub(RequestHandlerInterface::class);
$handler->method('handle')->willReturn(new Response());
$this->middleware->process(ServerRequestFactory::fromGlobals(), $handler);
$idAfterProcessingRequest = $this->middleware->currentRequestId();

View File

@@ -4,6 +4,7 @@ declare(strict_types=1);
namespace ShlinkioTest\Shlink\Core\EventDispatcher;
use PHPUnit\Framework\Attributes\AllowMockObjectsWithoutExpectations;
use PHPUnit\Framework\Attributes\Test;
use PHPUnit\Framework\MockObject\MockObject;
use PHPUnit\Framework\TestCase;
@@ -15,6 +16,7 @@ use Shlinkio\Shlink\Core\Visit\Geolocation\VisitToLocationHelperInterface;
use Shlinkio\Shlink\Core\Visit\Model\Visitor;
use Shlinkio\Shlink\IpGeolocation\Model\Location;
#[AllowMockObjectsWithoutExpectations]
class LocateUnlocatedVisitsTest extends TestCase
{
private LocateUnlocatedVisits $listener;

View File

@@ -83,7 +83,7 @@ class SendVisitToMatomoTest extends TestCase
$e = new Exception('Error!');
$this->em->expects($this->once())->method('find')->with(Visit::class, $visitId)->willReturn(
$this->createMock(Visit::class),
$this->createStub(Visit::class),
);
$this->visitSender->expects($this->once())->method('sendVisit')->willThrowException($e);
$this->logger->expects($this->never())->method('warning');

View File

@@ -93,11 +93,12 @@ class NotifyNewShortUrlToMercureTest extends TestCase
public function publishingIsSkippedIfNewShortUrlTopicIsNotEnabled(): void
{
$shortUrl = ShortUrl::withLongUrl('https://longUrl');
$update = Update::forTopicAndPayload('', []);
$this->em->expects($this->once())->method('find')->with(ShortUrl::class, '123')->willReturn($shortUrl);
$this->updatesGenerator->expects($this->never())->method('newShortUrlUpdate');
$this->helper->expects($this->never())->method('publishUpdate');
$this->logger->expects($this->never())->method('warning');
$this->logger->expects($this->never())->method('debug');
$this->listener(enableShortUrlTopic: false)(new ShortUrlCreated('123'));
}

View File

@@ -46,6 +46,7 @@ class NotifyNewShortUrlToRabbitMqTest extends TestCase
$this->em->expects($this->never())->method('find');
$this->logger->expects($this->never())->method('warning');
$this->logger->expects($this->never())->method('debug');
$this->updatesGenerator->expects($this->never())->method('newShortUrlUpdate');
($this->listener(false))(new ShortUrlCreated('123'));
}
@@ -61,6 +62,7 @@ class NotifyNewShortUrlToRabbitMqTest extends TestCase
);
$this->logger->expects($this->never())->method('debug');
$this->helper->expects($this->never())->method('publishUpdate');
$this->updatesGenerator->expects($this->never())->method('newShortUrlUpdate');
($this->listener())(new ShortUrlCreated($shortUrlId));
}

View File

@@ -52,6 +52,7 @@ class NotifyVisitToRabbitMqTest extends TestCase
$this->em->expects($this->never())->method('find');
$this->logger->expects($this->never())->method('warning');
$this->logger->expects($this->never())->method('debug');
$this->updatesGenerator->expects($this->never())->method('newVisitUpdate');
($this->listener(new RabbitMqOptions(enabled: false)))(new UrlVisited('123'));
}
@@ -67,6 +68,7 @@ class NotifyVisitToRabbitMqTest extends TestCase
);
$this->logger->expects($this->never())->method('debug');
$this->helper->expects($this->never())->method('publishUpdate');
$this->updatesGenerator->expects($this->never())->method('newVisitUpdate');
($this->listener())(new UrlVisited($visitId));
}
@@ -145,6 +147,8 @@ class NotifyVisitToRabbitMqTest extends TestCase
$this->em->expects($this->once())->method('find')->with(Visit::class, $visitId)->willReturn($visit);
$setup($this->updatesGenerator);
$expect($this->helper, $this->updatesGenerator);
$this->logger->expects($this->never())->method('warning');
$this->logger->expects($this->never())->method('debug');
($this->listener())(new UrlVisited($visitId));
}

View File

@@ -45,6 +45,7 @@ class NotifyNewShortUrlToRedisTest extends TestCase
$this->em->expects($this->never())->method('find');
$this->logger->expects($this->never())->method('warning');
$this->logger->expects($this->never())->method('debug');
$this->updatesGenerator->expects($this->never())->method('newShortUrlUpdate');
$this->createListener(false)(new ShortUrlCreated('123'));
}

View File

@@ -45,6 +45,7 @@ class NotifyVisitToRedisTest extends TestCase
$this->em->expects($this->never())->method('find');
$this->logger->expects($this->never())->method('warning');
$this->logger->expects($this->never())->method('debug');
$this->updatesGenerator->expects($this->never())->method('newOrphanVisitUpdate');
$this->createListener(false)(new UrlVisited('123'));
}

View File

@@ -125,6 +125,7 @@ class UpdateGeoLiteDbTest extends TestCase
$this->eventDispatcher->expects($this->exactly($expectedDispatches))->method('dispatch')->with(
new GeoLiteDbCreated(),
);
$this->logger->expects($this->never())->method('warning');
($this->listener)();
}

View File

@@ -8,6 +8,7 @@ use Cake\Chronos\Chronos;
use Closure;
use Doctrine\ORM\EntityManagerInterface;
use Doctrine\ORM\EntityRepository;
use PHPUnit\Framework\Attributes\AllowMockObjectsWithoutExpectations;
use PHPUnit\Framework\Attributes\DataProvider;
use PHPUnit\Framework\Attributes\Test;
use PHPUnit\Framework\MockObject\MockObject;
@@ -28,6 +29,7 @@ use Throwable;
use function array_map;
use function range;
#[AllowMockObjectsWithoutExpectations]
class GeolocationDbUpdaterTest extends TestCase
{
private MockObject & DbUpdaterInterface $dbUpdater;

View File

@@ -8,6 +8,7 @@ use Cake\Chronos\Chronos;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\EntityManagerInterface;
use PHPUnit\Framework\Assert;
use PHPUnit\Framework\Attributes\AllowMockObjectsWithoutExpectations;
use PHPUnit\Framework\Attributes\DataProvider;
use PHPUnit\Framework\Attributes\Test;
use PHPUnit\Framework\MockObject\MockObject;
@@ -43,6 +44,7 @@ use function Shlinkio\Shlink\Core\ArrayUtils\some;
use function sprintf;
use function str_contains;
#[AllowMockObjectsWithoutExpectations]
class ImportedLinksProcessorTest extends TestCase
{
private ImportedLinksProcessor $processor;

View File

@@ -9,6 +9,7 @@ use MatomoTracker;
use PHPUnit\Framework\Attributes\DataProvider;
use PHPUnit\Framework\Attributes\Test;
use PHPUnit\Framework\MockObject\MockObject;
use PHPUnit\Framework\MockObject\Stub;
use PHPUnit\Framework\TestCase;
use Shlinkio\Shlink\Common\Util\DateRange;
use Shlinkio\Shlink\Core\Config\Options\UrlShortenerOptions;
@@ -29,13 +30,13 @@ use function array_values;
class MatomoVisitSenderTest extends TestCase
{
private MockObject & MatomoTrackerBuilderInterface $trackerBuilder;
private MockObject & VisitIterationRepositoryInterface $visitIterationRepository;
private Stub & VisitIterationRepositoryInterface $visitIterationRepository;
private MatomoVisitSender $visitSender;
protected function setUp(): void
{
$this->trackerBuilder = $this->createMock(MatomoTrackerBuilderInterface::class);
$this->visitIterationRepository = $this->createMock(VisitIterationRepositoryInterface::class);
$this->visitIterationRepository = $this->createStub(VisitIterationRepositoryInterface::class);
$this->visitSender = new MatomoVisitSender(
$this->trackerBuilder,
@@ -155,13 +156,13 @@ class MatomoVisitSenderTest extends TestCase
$visitor = Visitor::empty();
$bot = Visitor::botInstance();
$this->visitIterationRepository->expects($this->once())->method('findAllVisits')->with($dateRange)->willReturn([
$this->visitIterationRepository->method('findAllVisits')->with($dateRange)->willReturn([
Visit::forBasePath($bot),
Visit::forValidShortUrl(ShortUrl::createFake(), $visitor),
Visit::forInvalidShortUrl($visitor),
]);
$tracker = $this->createMock(MatomoTracker::class);
$tracker = $this->createStub(MatomoTracker::class);
$tracker->method('setUrl')->willReturn($tracker);
$tracker->method('setUserAgent')->willReturn($tracker);
$tracker->method('setUrlReferrer')->willReturn($tracker);

View File

@@ -6,8 +6,10 @@ namespace ShlinkioTest\Shlink\Core\ShortUrl;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\EntityManagerInterface;
use PHPUnit\Framework\Attributes\AllowMockObjectsWithoutExpectations;
use PHPUnit\Framework\Attributes\Test;
use PHPUnit\Framework\MockObject\MockObject;
use PHPUnit\Framework\MockObject\Stub;
use PHPUnit\Framework\TestCase;
use Shlinkio\Shlink\Core\Config\Options\DeleteShortUrlsOptions;
use Shlinkio\Shlink\Core\Exception\DeleteShortUrlException;
@@ -24,10 +26,11 @@ use function array_map;
use function range;
use function sprintf;
#[AllowMockObjectsWithoutExpectations]
class DeleteShortUrlServiceTest extends TestCase
{
private MockObject & EntityManagerInterface $em;
private MockObject & ShortUrlResolverInterface $urlResolver;
private Stub & ShortUrlResolverInterface $urlResolver;
private MockObject & ExpiredShortUrlsRepository $expiredShortUrlsRepository;
private string $shortCode;
@@ -40,7 +43,7 @@ class DeleteShortUrlServiceTest extends TestCase
$this->em = $this->createMock(EntityManagerInterface::class);
$this->urlResolver = $this->createMock(ShortUrlResolverInterface::class);
$this->urlResolver = $this->createStub(ShortUrlResolverInterface::class);
$this->urlResolver->method('resolveShortUrl')->willReturn($shortUrl);
$this->expiredShortUrlsRepository = $this->createMock(ExpiredShortUrlsRepository::class);
@@ -51,6 +54,7 @@ class DeleteShortUrlServiceTest extends TestCase
{
$service = $this->createService();
$this->em->expects($this->never())->method('remove');
$this->expectException(DeleteShortUrlException::class);
$this->expectExceptionMessage(sprintf(
'Impossible to delete short URL with short code "%s", since it has more than "5" visits.',
@@ -91,10 +95,8 @@ class DeleteShortUrlServiceTest extends TestCase
{
$service = $this->createService(true, 100);
$this->em->expects($this->once())->method('remove')->with($this->isInstanceOf(ShortUrl::class))->willReturn(
null,
);
$this->em->expects($this->once())->method('flush')->with()->willReturn(null);
$this->em->expects($this->once())->method('remove')->with($this->isInstanceOf(ShortUrl::class));
$this->em->expects($this->once())->method('flush');
$service->deleteByShortCode(ShortUrlIdentifier::fromShortCodeAndDomain($this->shortCode));
}

View File

@@ -39,6 +39,7 @@ class ShortUrlTitleResolutionHelperTest extends TestCase
{
$data = ShortUrlCreation::fromRawData(['longUrl' => self::LONG_URL]);
$this->httpClient->expects($this->never())->method('request');
$this->logger->expects($this->never())->method('warning');
$result = $this->helper()->processTitle($data);
@@ -53,6 +54,7 @@ class ShortUrlTitleResolutionHelperTest extends TestCase
'title' => 'foo',
]);
$this->httpClient->expects($this->never())->method('request');
$this->logger->expects($this->never())->method('warning');
$result = $this->helper(autoResolveTitles: true)->processTitle($data);
@@ -64,6 +66,7 @@ class ShortUrlTitleResolutionHelperTest extends TestCase
{
$data = ShortUrlCreation::fromRawData(['longUrl' => self::LONG_URL]);
$this->expectRequestToBeCalled()->willThrowException(new Exception('Error'));
$this->logger->expects($this->never())->method('warning');
$result = $this->helper(autoResolveTitles: true)->processTitle($data);
@@ -75,6 +78,7 @@ class ShortUrlTitleResolutionHelperTest extends TestCase
{
$data = ShortUrlCreation::fromRawData(['longUrl' => self::LONG_URL]);
$this->expectRequestToBeCalled()->willReturn(new JsonResponse(['foo' => 'bar']));
$this->logger->expects($this->never())->method('warning');
$result = $this->helper(autoResolveTitles: true)->processTitle($data);
@@ -86,6 +90,7 @@ class ShortUrlTitleResolutionHelperTest extends TestCase
{
$data = ShortUrlCreation::fromRawData(['longUrl' => self::LONG_URL]);
$this->expectRequestToBeCalled()->willReturn($this->respWithoutTitle());
$this->logger->expects($this->never())->method('warning');
$result = $this->helper(autoResolveTitles: true)->processTitle($data);
@@ -151,8 +156,6 @@ class ShortUrlTitleResolutionHelperTest extends TestCase
self::assertEquals('Resolved "title"', $result->title);
}
/**
*/
private function expectRequestToBeCalled(): InvocationStubber
{
return $this->httpClient->expects($this->once())->method('request')->with(

View File

@@ -13,6 +13,7 @@ use PHPUnit\Framework\Attributes\DataProvider;
use PHPUnit\Framework\Attributes\Test;
use PHPUnit\Framework\Attributes\TestWith;
use PHPUnit\Framework\MockObject\MockObject;
use PHPUnit\Framework\MockObject\Stub;
use PHPUnit\Framework\TestCase;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\RequestHandlerInterface;
@@ -40,7 +41,7 @@ class ExtraPathRedirectMiddlewareTest extends TestCase
private MockObject & RequestTrackerInterface $requestTracker;
private MockObject & ShortUrlRedirectionBuilderInterface $redirectionBuilder;
private MockObject & RedirectResponseHelperInterface $redirectResponseHelper;
private MockObject & RequestHandlerInterface $handler;
private Stub & RequestHandlerInterface $handler;
protected function setUp(): void
{
@@ -48,7 +49,7 @@ class ExtraPathRedirectMiddlewareTest extends TestCase
$this->requestTracker = $this->createMock(RequestTrackerInterface::class);
$this->redirectionBuilder = $this->createMock(ShortUrlRedirectionBuilderInterface::class);
$this->redirectResponseHelper = $this->createMock(RedirectResponseHelperInterface::class);
$this->handler = $this->createMock(RequestHandlerInterface::class);
$this->handler = $this->createStub(RequestHandlerInterface::class);
$this->handler->method('handle')->willReturn(new RedirectResponse(''));
}
@@ -66,7 +67,6 @@ class ExtraPathRedirectMiddlewareTest extends TestCase
$this->requestTracker->expects($this->never())->method('trackIfApplicable');
$this->redirectionBuilder->expects($this->never())->method('buildShortUrlRedirect');
$this->redirectResponseHelper->expects($this->never())->method('buildRedirectResponse');
$this->handler->expects($this->once())->method('handle');
$this->middleware($options)->process($request, $this->handler);
}
@@ -116,7 +116,7 @@ class ExtraPathRedirectMiddlewareTest extends TestCase
extraPathMode: ExtraPathMode::APPEND,
);
$type = $this->createMock(NotFoundType::class);
$type = $this->createStub(NotFoundType::class);
$type->method('isRegularNotFound')->willReturn(true);
$type->method('isInvalidShortUrl')->willReturn(true);
$request = ServerRequestFactory::fromGlobals()->withAttribute(NotFoundType::class, $type)
@@ -144,7 +144,7 @@ class ExtraPathRedirectMiddlewareTest extends TestCase
extraPathMode: $extraPathMode,
);
$type = $this->createMock(NotFoundType::class);
$type = $this->createStub(NotFoundType::class);
$type->method('isRegularNotFound')->willReturn(true);
$type->method('isInvalidShortUrl')->willReturn(true);
$request = ServerRequestFactory::fromGlobals()->withAttribute(NotFoundType::class, $type)

View File

@@ -116,7 +116,7 @@ class PersistenceShortUrlRelationResolverTest extends TestCase
{
$repo = $this->createMock(DomainRepository::class);
$repo->expects($this->exactly(3))->method('findOneBy')->with($this->isArray())->willReturn(null);
$this->em->method('getRepository')->willReturn($repo);
$this->em->expects($this->atLeastOnce())->method('getRepository')->willReturn($repo);
$authority = 'foo.com';
$domain1 = $this->resolver->resolveDomain($authority);
@@ -135,7 +135,7 @@ class PersistenceShortUrlRelationResolverTest extends TestCase
{
$tagRepo = $this->createMock(TagRepository::class);
$tagRepo->expects($this->exactly(6))->method('findOneBy')->with($this->isArray())->willReturn(null);
$this->em->method('getRepository')->willReturn($tagRepo);
$this->em->expects($this->atLeastOnce())->method('getRepository')->willReturn($tagRepo);
$tags = ['foo', 'bar'];
[$foo1, $bar1] = $this->resolver->resolveTags($tags);

View File

@@ -29,15 +29,11 @@ class ShortUrlServiceTest extends TestCase
protected function setUp(): void
{
$em = $this->createMock(EntityManagerInterface::class);
$em->method('persist')->willReturn(null);
$em->method('flush')->willReturn(null);
$this->urlResolver = $this->createMock(ShortUrlResolverInterface::class);
$this->titleResolutionHelper = $this->createMock(ShortUrlTitleResolutionHelperInterface::class);
$this->service = new ShortUrlService(
$em,
$this->createStub(EntityManagerInterface::class),
$this->urlResolver,
$this->titleResolutionHelper,
new SimpleShortUrlRelationResolver(),

View File

@@ -7,6 +7,7 @@ namespace ShlinkioTest\Shlink\Core\ShortUrl;
use Cake\Chronos\Chronos;
use Doctrine\ORM\EntityManagerInterface;
use Laminas\ServiceManager\Exception\ServiceNotFoundException;
use PHPUnit\Framework\Attributes\AllowMockObjectsWithoutExpectations;
use PHPUnit\Framework\Attributes\DataProvider;
use PHPUnit\Framework\Attributes\Test;
use PHPUnit\Framework\MockObject\MockObject;
@@ -21,10 +22,10 @@ use Shlinkio\Shlink\Core\ShortUrl\Repository\ShortUrlRepositoryInterface;
use Shlinkio\Shlink\Core\ShortUrl\Resolver\SimpleShortUrlRelationResolver;
use Shlinkio\Shlink\Core\ShortUrl\UrlShortener;
#[AllowMockObjectsWithoutExpectations]
class UrlShortenerTest extends TestCase
{
private UrlShortener $urlShortener;
private MockObject & EntityManagerInterface $em;
private MockObject & ShortUrlTitleResolutionHelperInterface $titleResolutionHelper;
private MockObject & ShortCodeUniquenessHelperInterface $shortCodeHelper;
private MockObject & EventDispatcherInterface $dispatcher;
@@ -35,16 +36,16 @@ class UrlShortenerTest extends TestCase
$this->titleResolutionHelper = $this->createMock(ShortUrlTitleResolutionHelperInterface::class);
$this->shortCodeHelper = $this->createMock(ShortCodeUniquenessHelperInterface::class);
$this->em = $this->createMock(EntityManagerInterface::class);
$this->em->method('persist')->willReturnCallback(fn (ShortUrl $shortUrl) => $shortUrl->setId('10'));
$this->em->method('wrapInTransaction')->willReturnCallback(fn (callable $callback) => $callback());
$em = $this->createStub(EntityManagerInterface::class);
$em->method('persist')->willReturnCallback(fn (ShortUrl $shortUrl) => $shortUrl->setId('10'));
$em->method('wrapInTransaction')->willReturnCallback(fn (callable $callback) => $callback());
$this->dispatcher = $this->createMock(EventDispatcherInterface::class);
$this->repo = $this->createMock(ShortUrlRepositoryInterface::class);
$this->urlShortener = new UrlShortener(
$this->titleResolutionHelper,
$this->em,
$em,
new SimpleShortUrlRelationResolver(),
$this->shortCodeHelper,
$this->dispatcher,

View File

@@ -28,15 +28,12 @@ use ShlinkioTest\Shlink\Core\Util\ApiKeyDataProviders;
class TagServiceTest extends TestCase
{
private TagService $service;
private MockObject & EntityManagerInterface $em;
private MockObject & TagRepository $repo;
protected function setUp(): void
{
$this->em = $this->createMock(EntityManagerInterface::class);
$this->repo = $this->createMock(TagRepository::class);
$this->service = new TagService($this->em, $this->repo);
$this->service = new TagService($this->createStub(EntityManagerInterface::class), $this->repo);
}
#[Test]
@@ -136,7 +133,6 @@ class TagServiceTest extends TestCase
$this->repo->expects($this->once())->method('findOneBy')->willReturn($expected);
$this->repo->expects($this->exactly($count > 0 ? 0 : 1))->method('count')->willReturn($count);
$this->em->expects($this->once())->method('flush');
$tag = $this->service->renameTag(Renaming::fromNames($oldName, $newName));
@@ -155,7 +151,6 @@ class TagServiceTest extends TestCase
{
$this->repo->expects($this->once())->method('findOneBy')->willReturn(new Tag('foo'));
$this->repo->expects($this->once())->method('count')->willReturn(1);
$this->em->expects($this->never())->method('flush');
$this->expectException(TagConflictException::class);

View File

@@ -52,6 +52,9 @@ class RequestTrackerTest extends TestCase
public function trackingIsDisabledWhenRequestDoesNotMeetConditions(ServerRequestInterface $request): void
{
$this->visitsTracker->expects($this->never())->method('track');
$this->notFoundType->expects($this->never())->method('isBaseUrl');
$this->notFoundType->expects($this->never())->method('isRegularNotFound');
$this->notFoundType->expects($this->never())->method('isInvalidShortUrl');
$shortUrl = ShortUrl::withLongUrl(self::LONG_URL);
$this->requestTracker->trackIfApplicable($shortUrl, $request);
@@ -89,6 +92,9 @@ class RequestTrackerTest extends TestCase
$shortUrl,
$this->isInstanceOf(Visitor::class),
);
$this->notFoundType->expects($this->never())->method('isBaseUrl');
$this->notFoundType->expects($this->never())->method('isRegularNotFound');
$this->notFoundType->expects($this->never())->method('isInvalidShortUrl');
$this->requestTracker->trackIfApplicable($shortUrl, $this->request);
}
@@ -101,6 +107,9 @@ class RequestTrackerTest extends TestCase
$shortUrl,
$this->isInstanceOf(Visitor::class),
);
$this->notFoundType->expects($this->never())->method('isBaseUrl');
$this->notFoundType->expects($this->never())->method('isRegularNotFound');
$this->notFoundType->expects($this->never())->method('isInvalidShortUrl');
$this->requestTracker->trackIfApplicable($shortUrl, ServerRequestFactory::fromGlobals()->withAttribute(
IP_ADDRESS_REQUEST_ATTRIBUTE,
@@ -159,6 +168,9 @@ class RequestTrackerTest extends TestCase
$this->visitsTracker->expects($this->never())->method('trackBaseUrlVisit');
$this->visitsTracker->expects($this->never())->method('trackRegularNotFoundVisit');
$this->visitsTracker->expects($this->never())->method('trackInvalidShortUrlVisit');
$this->notFoundType->expects($this->never())->method('isBaseUrl');
$this->notFoundType->expects($this->never())->method('isRegularNotFound');
$this->notFoundType->expects($this->never())->method('isInvalidShortUrl');
$this->requestTracker->trackNotFoundIfApplicable($request);
}

View File

@@ -110,7 +110,7 @@ class VisitsStatsHelperTest extends TestCase
static fn () => Visit::forValidShortUrl(ShortUrl::createFake(), Visitor::empty()),
range(0, 1),
);
$repo2 = $this->createMock(VisitRepository::class);
$repo2 = $this->createStub(VisitRepository::class);
$repo2->method('findVisitsByShortCode')->willReturn($list);
$repo2->method('countVisitsByShortCode')->willReturn(1);
@@ -164,7 +164,7 @@ class VisitsStatsHelperTest extends TestCase
static fn () => Visit::forValidShortUrl(ShortUrl::createFake(), Visitor::empty()),
range(0, 1),
);
$repo2 = $this->createMock(VisitRepository::class);
$repo2 = $this->createStub(VisitRepository::class);
$repo2->method('findVisitsByTag')->willReturn($list);
$repo2->method('countVisitsByTag')->willReturn(1);
@@ -203,7 +203,7 @@ class VisitsStatsHelperTest extends TestCase
static fn () => Visit::forValidShortUrl(ShortUrl::createFake(), Visitor::empty()),
range(0, 1),
);
$repo2 = $this->createMock(VisitRepository::class);
$repo2 = $this->createStub(VisitRepository::class);
$repo2->method('findVisitsByDomain')->willReturn($list);
$repo2->method('countVisitsByDomain')->willReturn(1);
@@ -227,7 +227,7 @@ class VisitsStatsHelperTest extends TestCase
static fn () => Visit::forValidShortUrl(ShortUrl::createFake(), Visitor::empty()),
range(0, 1),
);
$repo2 = $this->createMock(VisitRepository::class);
$repo2 = $this->createStub(VisitRepository::class);
$repo2->method('findVisitsByDomain')->willReturn($list);
$repo2->method('countVisitsByDomain')->willReturn(1);

View File

@@ -25,11 +25,11 @@ class HealthActionTest extends TestCase
protected function setUp(): void
{
$this->conn = $this->createMock(Connection::class);
$dbPlatform = $this->createMock(AbstractPlatform::class);
$dbPlatform = $this->createStub(AbstractPlatform::class);
$dbPlatform->method('getDummySelectSQL')->willReturn('');
$this->conn->method('getDatabasePlatform')->willReturn($dbPlatform);
$em = $this->createMock(EntityManagerInterface::class);
$em = $this->createStub(EntityManagerInterface::class);
$em->method('getConnection')->willReturn($this->conn);
$this->action = new HealthAction($em, new AppOptions(version: '1.2.3'));
@@ -38,7 +38,7 @@ class HealthActionTest extends TestCase
#[Test]
public function passResponseIsReturnedWhenDummyQuerySucceeds(): void
{
$this->conn->expects($this->once())->method('executeQuery')->willReturn($this->createMock(Result::class));
$this->conn->expects($this->once())->method('executeQuery')->willReturn($this->createStub(Result::class));
/** @var JsonResponse $resp */
$resp = $this->action->handle(new ServerRequest());

View File

@@ -7,6 +7,7 @@ namespace ShlinkioTest\Shlink\Rest\Action;
use Cake\Chronos\Chronos;
use Laminas\Diactoros\Response\JsonResponse;
use Laminas\Diactoros\ServerRequestFactory;
use PHPUnit\Framework\Attributes\AllowMockObjectsWithoutExpectations;
use PHPUnit\Framework\Attributes\DataProvider;
use PHPUnit\Framework\Attributes\Test;
use PHPUnit\Framework\MockObject\MockObject;
@@ -78,7 +79,7 @@ class MercureInfoActionTest extends TestCase
yield 'days defined' => [10];
}
#[Test]
#[Test, AllowMockObjectsWithoutExpectations]
public function getRouteDefReturnsExpectedData(): void
{
self::assertEquals([

View File

@@ -25,7 +25,7 @@ class SingleStepCreateShortUrlActionTest extends TestCase
protected function setUp(): void
{
$this->urlShortener = $this->createMock(UrlShortenerInterface::class);
$transformer = $this->createMock(ShortUrlDataTransformerInterface::class);
$transformer = $this->createStub(ShortUrlDataTransformerInterface::class);
$transformer->method('transform')->willReturn([]);
$this->action = new SingleStepCreateShortUrlAction(

View File

@@ -33,6 +33,7 @@ class UpdateTagActionTest extends TestCase
{
$request = $this->requestWithApiKey()->withParsedBody($bodyParams);
$this->tagService->expects($this->never())->method('renameTag');
$this->expectException(ValidationException::class);
$this->action->handle($request);

View File

@@ -55,7 +55,9 @@ class OrphanVisitsActionTest extends TestCase
#[Test]
public function exceptionIsThrownIfInvalidDataIsProvided(): void
{
$this->visitsHelper->expects($this->never())->method('orphanVisits');
$this->expectException(ValidationException::class);
$this->action->handle(
ServerRequestFactory::fromGlobals()
->withAttribute(ApiKey::class, ApiKey::create())

View File

@@ -48,7 +48,7 @@ class CrossDomainMiddlewareTest extends TestCase
$originalResponse = new Response();
$this->handler->expects($this->once())->method('handle')->willReturn($originalResponse);
$response = $this->middleware()->process((new ServerRequest())->withHeader('Origin', 'local'), $this->handler);
$response = $this->middleware()->process(new ServerRequest()->withHeader('Origin', 'local'), $this->handler);
self::assertNotSame($originalResponse, $response);
$headers = $response->getHeaders();
@@ -63,7 +63,7 @@ class CrossDomainMiddlewareTest extends TestCase
public function optionsRequestIncludesMoreHeaders(): void
{
$originalResponse = new Response();
$request = (new ServerRequest())
$request = new ServerRequest()
->withMethod('OPTIONS')
->withHeader('Origin', 'local')
->withHeader('Access-Control-Request-Headers', 'foo, bar, baz');
@@ -90,8 +90,8 @@ class CrossDomainMiddlewareTest extends TestCase
if ($allowHeader !== null) {
$originalResponse = $originalResponse->withHeader('Allow', $allowHeader);
}
$request = (new ServerRequest())->withHeader('Origin', 'local')
->withMethod('OPTIONS');
$request = new ServerRequest()->withHeader('Origin', 'local')
->withMethod('OPTIONS');
$this->handler->expects($this->once())->method('handle')->willReturn($originalResponse);
$response = $this->middleware()->process($request, $this->handler);
@@ -113,9 +113,9 @@ class CrossDomainMiddlewareTest extends TestCase
int $status,
int $expectedStatus,
): void {
$originalResponse = (new Response())->withStatus($status);
$request = (new ServerRequest())->withMethod($method)
->withHeader('Origin', 'local');
$originalResponse = new Response()->withStatus($status);
$request = new ServerRequest()->withMethod($method)
->withHeader('Origin', 'local');
$this->handler->expects($this->once())->method('handle')->willReturn($originalResponse);
$response = $this->middleware()->process($request, $this->handler);
@@ -152,10 +152,10 @@ class CrossDomainMiddlewareTest extends TestCase
public function credentialsAreAllowedIfConfiguredSo(bool $allowCredentials, string $method): void
{
$originalResponse = new Response();
$request = (new ServerRequest())
$request = new ServerRequest()
->withMethod($method)
->withHeader('Origin', 'local');
$this->handler->method('handle')->willReturn($originalResponse);
$this->handler->expects($this->once())->method('handle')->willReturn($originalResponse);
$response = $this->middleware(allowCredentials: $allowCredentials)->process($request, $this->handler);
$headers = $response->getHeaders();

View File

@@ -30,7 +30,7 @@ class CreateShortUrlContentNegotiationMiddlewareTest extends TestCase
public function whenNoJsonResponseIsReturnedNoFurtherOperationsArePerformed(): void
{
$expectedResp = new Response();
$this->requestHandler->method('handle')->willReturn($expectedResp);
$this->requestHandler->expects($this->once())->method('handle')->willReturn($expectedResp);
$resp = $this->middleware->process(new ServerRequest(), $this->requestHandler);
@@ -40,7 +40,7 @@ class CreateShortUrlContentNegotiationMiddlewareTest extends TestCase
#[Test, DataProvider('provideData')]
public function properResponseIsReturned(string|null $accept, array $query, string $expectedContentType): void
{
$request = (new ServerRequest())->withQueryParams($query);
$request = new ServerRequest()->withQueryParams($query);
if ($accept !== null) {
$request = $request->withHeader('Accept', $accept);
}

View File

@@ -6,6 +6,7 @@ namespace ShlinkioTest\Shlink\Rest\Service;
use Cake\Chronos\Chronos;
use Doctrine\ORM\EntityManager;
use PHPUnit\Framework\Attributes\AllowMockObjectsWithoutExpectations;
use PHPUnit\Framework\Attributes\DataProvider;
use PHPUnit\Framework\Attributes\Test;
use PHPUnit\Framework\Attributes\TestWith;
@@ -24,6 +25,7 @@ use Shlinkio\Shlink\Rest\Service\ApiKeyService;
use function substr;
#[AllowMockObjectsWithoutExpectations]
class ApiKeyServiceTest extends TestCase
{
private ApiKeyService $service;