Skip to content

Commit a08c746

Browse files
committed
add simple test for AddUserCommand
1 parent abac25f commit a08c746

File tree

1 file changed

+95
-0
lines changed

1 file changed

+95
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,95 @@
1+
<?php
2+
3+
/*
4+
* This file is part of the Symfony package.
5+
*
6+
* (c) Fabien Potencier <[email protected]>
7+
*
8+
* For the full copyright and license information, please view the LICENSE
9+
* file that was distributed with this source code.
10+
*/
11+
12+
namespace Tests\Command;
13+
14+
use AppBundle\Command\AddUserCommand;
15+
use AppBundle\Entity\User;
16+
use Symfony\Bundle\FrameworkBundle\Console\Application;
17+
use Symfony\Bundle\FrameworkBundle\Test\KernelTestCase;
18+
use Symfony\Component\Console\Tester\CommandTester;
19+
20+
class AddUserCommandTest extends KernelTestCase
21+
{
22+
private function executeCommand(array $inputArgs, array $interactiveInputs = [])
23+
{
24+
self::bootKernel();
25+
26+
$command = new AddUserCommand();
27+
$command->setApplication(new Application(self::$kernel));
28+
29+
$commandTester = new CommandTester($command);
30+
$commandTester->setInputs($interactiveInputs);
31+
$commandTester->execute($inputArgs);
32+
}
33+
34+
/**
35+
* @param bool $isAdmin
36+
*/
37+
private function assertUserCreated($isAdmin)
38+
{
39+
$container = self::$kernel->getContainer();
40+
41+
/** @var User $user */
42+
$user = $container->get('doctrine')->getRepository(User::class)->findOneByEmail('[email protected]');
43+
$this->assertNotNull($user);
44+
45+
$this->assertSame('Chuck Norris', $user->getFullName());
46+
$this->assertSame('chuck_norris', $user->getUsername());
47+
$this->assertTrue($container->get('security.password_encoder')->isPasswordValid($user, 'foobar'));
48+
$this->assertSame($isAdmin ? ['ROLE_ADMIN'] : ['ROLE_USER'], $user->getRoles());
49+
}
50+
51+
/**
52+
* @dataProvider isAdminDataProvider
53+
*
54+
* @param bool $isAdmin
55+
*/
56+
public function testCreateUserNonInteractive($isAdmin)
57+
{
58+
$input = [
59+
'username' => 'chuck_norris',
60+
'password' => 'foobar',
61+
'email' => '[email protected]',
62+
'full-name' => 'Chuck Norris',
63+
];
64+
65+
if ($isAdmin) {
66+
$input['--admin'] = 1;
67+
}
68+
69+
$this->executeCommand($input);
70+
$this->assertUserCreated($isAdmin);
71+
}
72+
73+
/**
74+
* @dataProvider isAdminDataProvider
75+
*
76+
* @param bool $isAdmin
77+
*/
78+
public function testCreateUserInteractive($isAdmin)
79+
{
80+
// see https://symfony.com/doc/current/components/console/helpers/questionhelper.html#testing-a-command-that-expects-input
81+
$this->executeCommand($isAdmin ? ['--admin' => 1] : [], [
82+
'chuck_norris',
83+
'foobar',
84+
85+
'Chuck Norris',
86+
]);
87+
$this->assertUserCreated($isAdmin);
88+
}
89+
90+
public function isAdminDataProvider()
91+
{
92+
yield [true];
93+
yield [false];
94+
}
95+
}

0 commit comments

Comments
 (0)