John Davidson

php - Symfony - test properly voter class


I have trouble writing test for my custom voter in Symfony as I am new at writing test:

This is part of the code I want to test:

protected function voteOnAttribute(
string $attribute,
TokenInterface $token
): bool
$user = $token->getUser();
if (!$user instanceof UserInterface) {
return false;

return match ($attribute) {
'read' => $this->canRead($member, $subject),
'create' => $this->canCreate($member, $subject),
default => throw new Exception(sprintf('Unhandled attribute "%s"', $attribute))

And this is my test class:

protected $token;

public function setUp(): void
$this->token = $this->createMock(TokenInterface::class);
'fistName' => 'Jonh',
'lastName' => 'Doe',
'email' => '[email protected]'

* @dataProvider provideCases
public function testVote(
array $attributes,
string $subject,
?TokenInterface $token,
) {
$voter = new RoleVoter();
$this->assertEquals($expectedVote, $voter->vote($this->token, $subject, $attributes));

public function provideCases(): \Generator
yield 'user cannot read' => [

yield 'user can read' => [

And I always get:

testVote with data set "user can read" (array('read'), 'customers',
null, 1) Failed asserting that -1 matches expected 1.

I would really appreciate if someone would help me continue with this.. Thanks

My Answer:

if (!$user instanceof User) {
// the user must be logged in; if not, deny access
return false;

switch ($attribute) {
case 'EDIT':
// logic to determine if the user can edit the subject
case 'DELETE':
// logic to determine if the user can delete the subject

return false;

Here is an example of how you can write a test for this voter class using PHPUnit:

use App\Security\Voter\CustomVoter;
use PHPUnit\Framework\TestCase;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use App\Entity\User;

class CustomVoterTest extends TestCase
public function testVoteOnAttribute()
$voter = new CustomVoter();

$user = new User(); // create a mock User object
$token = $this->createMock(TokenInterface::class);

$this->assertFalse($voter->voteOnAttribute('EDIT', null, $token));
$this->assertFalse($voter->voteOnAttribute('DELETE', null, $token));

In this test, we create an instance of the `CustomVoter` class and mock a `TokenInterface` object with a mock `User` object. We then call the `voteOnAttribute` method with different attributes and assert that the method returns `false` for both cases.

You can expand this test by adding more test cases for different scenarios and attributes to ensure that your voter class behaves as expected in various situations.

Rate this post

3 of 5 based on 7473 votes


© 2024 - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us