Testing a getter and a setter at the same time in a PHPUnit test
Published on 2022-10-26 • Modified on 2022-10-26
This snippet shows how to test a getter and a setter simultaneously in a PHPUnit test case. This small trick allows us to gain space and test both functions on the same line thanks to the fluent interface of the class. You can use a data provider if you don't want to duplicate the tested value.
<?php
declare(strict_types=1);
namespace App\Tests\Unit\Entity;
use App\Entity\Article;
use PHPUnit\Framework\TestCase;
final class ArticleTest extends TestCase
{
public function testArticleIcon(): void
{
self::assertNull((new Article())->getIcon()); // initial value, field is nullable
self::assertSame('icon', (new Article())->setIcon('icon')->getIcon());
}
/**
* @return iterable<array{0: string}>
*/
public function providerForArticleIconWithProvider(): iterable
{
yield ['foo'];
yield [''];
}
/**
* @dataProvider providerForArticleIconWithProvider
*/
public function testArticleIconWithProvider(string $value): void
{
self::assertSame($value, (new Article())->setIcon($value)->getIcon());
}
}
More on Stackoverflow More on the web Random snippet