|
15 | 15 | use PHPUnit\Framework\Constraint\LogicalNot;
|
16 | 16 | use Symfony\Bundle\FrameworkBundle\KernelBrowser;
|
17 | 17 | use Symfony\Component\BrowserKit\Test\Constraint as BrowserKitConstraint;
|
| 18 | +use Symfony\Component\DependencyInjection\Exception\ServiceNotFoundException; |
18 | 19 | use Symfony\Component\DomCrawler\Crawler;
|
19 | 20 | use Symfony\Component\DomCrawler\Test\Constraint as DomCrawlerConstraint;
|
20 | 21 | use Symfony\Component\HttpFoundation\Request;
|
|
28 | 29 | */
|
29 | 30 | trait WebTestAssertionsTrait
|
30 | 31 | {
|
| 32 | + /** |
| 33 | + * Creates a KernelBrowser. |
| 34 | + * |
| 35 | + * @param array $options An array of options to pass to the createKernel method |
| 36 | + * @param array $server An array of server parameters |
| 37 | + * |
| 38 | + * @return KernelBrowser A KernelBrowser instance |
| 39 | + */ |
| 40 | + protected static function createClient(array $options = [], array $server = []) |
| 41 | + { |
| 42 | + $kernel = static::bootKernel($options); |
| 43 | + |
| 44 | + try { |
| 45 | + $client = $kernel->getContainer()->get('test.client'); |
| 46 | + } catch (ServiceNotFoundException $e) { |
| 47 | + if (class_exists(KernelBrowser::class)) { |
| 48 | + throw new \LogicException('You cannot create the client used in functional tests if the "framework.test" config is not set to true.'); |
| 49 | + } |
| 50 | + throw new \LogicException('You cannot create the client used in functional tests if the BrowserKit component is not available. Try running "composer require symfony/browser-kit"'); |
| 51 | + } |
| 52 | + |
| 53 | + $client->setServerParameters($server); |
| 54 | + |
| 55 | + return self::getClient($client); |
| 56 | + } |
| 57 | + |
31 | 58 | public static function assertResponseIsSuccessful(string $message = ''): void
|
32 | 59 | {
|
33 | 60 | self::assertThat(static::getResponse(), new ResponseConstraint\ResponseIsSuccessful(), $message);
|
@@ -186,13 +213,19 @@ public static function assertRouteSame($expectedRoute, array $parameters = [], s
|
186 | 213 | self::assertThat(static::getRequest(), $constraint, $message);
|
187 | 214 | }
|
188 | 215 |
|
189 |
| - private static function getClient(): KernelBrowser |
| 216 | + private static function getClient(KernelBrowser $newClient = null): ?KernelBrowser |
190 | 217 | {
|
191 |
| - if (!static::$client instanceof KernelBrowser) { |
| 218 | + static $client; |
| 219 | + |
| 220 | + if (0 < \func_num_args()) { |
| 221 | + return $client = $newClient; |
| 222 | + } |
| 223 | + |
| 224 | + if (!$client instanceof KernelBrowser) { |
192 | 225 | static::fail(\sprintf('A client must be set to make assertions on it. Did you forget to call "%s::createClient"?', __CLASS__));
|
193 | 226 | }
|
194 | 227 |
|
195 |
| - return static::$client; |
| 228 | + return $client; |
196 | 229 | }
|
197 | 230 |
|
198 | 231 | private static function getCrawler(): Crawler
|
|
0 commit comments