Aserciones de la prueba JSON y siembra de la base de datos
Keep on Learning!
If you liked what you've learned so far, dive in! Subscribe to get access to this tutorial plus video, code and script downloads.
With a Subscription, click any sentence in the script to jump to that part of the video!
Login SubscribeHagamos realidad esta prueba con datos y aserciones.
Hay dos formas principales de hacer aserciones con Browser. En primer lugar, viene con un montón de métodos incorporados para ayudarte, como ->assertJson(). O... siempre puedes coger el JSON que vuelve de una ruta y comprobar las cosas utilizando las aserciones incorporadas de PHPUnit que conoces y adoras. Veremos ambas cosas.
Empecemos comprobando ->assertJson():
| // ... lines 1 - 8 | |
| class DragonTreasureResourceTest extends KernelTestCase | |
| { | |
| // ... lines 11 - 13 | |
| public function testGetCollectionOfTreasures(): void | |
| { | |
| $this->browser() | |
| ->get('/api/treasures') | |
| // ... line 18 | |
| ->assertJson() | |
| ; | |
| } | |
| } |
Cuando lo ejecutemos:
symfony php bin/phpunit
¡Pasa! ¡Genial! Sabemos que esta respuesta debe tener una propiedad hydra:totalItemsestablecida en el número de resultados. Ahora mismo, nuestra base de datos está vacía... pero al menos podemos afirmar que coincide con cero.
Para ello, utiliza ->assertJsonMatches().
Se trata de un método especial de Browser que utiliza una sintaxis especial que nos permite leer diferentes partes del JSON. Profundizaremos en ello dentro de un minuto.
Pero éste es sencillo: afirma que hydra:totalItems es igual a 0:
| // ... lines 1 - 8 | |
| class DragonTreasureResourceTest extends KernelTestCase | |
| { | |
| // ... lines 11 - 13 | |
| public function testGetCollectionOfTreasures(): void | |
| { | |
| $this->browser() | |
| // ... lines 17 - 18 | |
| ->assertJson() | |
| ->assertJsonMatches('hydra:totalItems', 0) | |
| ; | |
| } | |
| } |
Cuando intentamos esto
symfony php bin/phpunit
¡Falla! Pero con un gran error:
mtdowling/jmespath.phpes necesario para buscar JSON
Hola JMESPath
Ah, ¡necesitamos instalarlo! Copia la línea composer require, busca tu terminal y ejecútalo:
composer require mtdowling/jmespath.php --dev
Esto de "JMESPath" es en realidad superguay: es un "lenguaje de consulta" para leer distintas partes de cualquier JSON. Por ejemplo, si éste es tu JSON y quieres leer la clave a, sólo tienes que decir a. Sencillo.
Pero también puedes hacer cosas más profundas, como a.b.c.d. O ponte más loco: coge el índice 1, o coge a.b.c, luego el índice 0, .d, el índice 1 y luego el índice 0. Incluso puedes cortar la matriz de diferentes maneras. Básicamente... puedes volverte loco.
Pero no vamos a perder la cabeza con esto. Es una sintaxis práctica... pero si las cosas se ponen demasiado complejas, siempre podemos probar el JSON manualmente, cosa que haremos dentro de un rato.
De todos modos, ahora que tenemos la biblioteca instalada, volvamos a ejecutar la prueba.
symfony php bin/phpunit
¡Sigue fallando! Con un extraño error:
Error de sintaxis en el carácter 5
hydra:totalItems.
Por desgracia, el : es un carácter especial dentro de JMESPath. Así que siempre que tengamos un :, tenemos que poner comillas alrededor de esa clave:
| // ... lines 1 - 8 | |
| class DragonTreasureResourceTest extends KernelTestCase | |
| { | |
| // ... lines 11 - 13 | |
| public function testGetCollectionOfTreasures(): void | |
| { | |
| $this->browser() | |
| // ... lines 17 - 19 | |
| ->assertJsonMatches('"hydra:totalItems"', 0) | |
| ; | |
| } | |
| } |
No es lo ideal, pero no es un gran inconveniente.
Ahora, cuando lo probamos
symfony php bin/phpunit
¡Pasa!
Sembrar la base de datos
Pero... ésta no es una prueba muy interesante: sólo estamos afirmando que no obtenemos nada de vuelta... porque la base de datos está vacía. Para que nuestra prueba sea real, necesitamos datos: necesitamos sembrar la base de datos con datos al inicio de la prueba.
Afortunadamente, Foundry lo hace muy sencillo. Arriba, llama aDragonTreasureFactory::createMany() y creemos 5 tesoros. Ahora, abajo, afirma que obtenemos 5 resultados:
| // ... lines 1 - 4 | |
| use App\Factory\DragonTreasureFactory; | |
| // ... lines 6 - 9 | |
| class DragonTreasureResourceTest extends KernelTestCase | |
| { | |
| // ... lines 12 - 14 | |
| public function testGetCollectionOfTreasures(): void | |
| { | |
| DragonTreasureFactory::createMany(5); | |
| $this->browser() | |
| // ... lines 20 - 22 | |
| ->assertJsonMatches('"hydra:totalItems"', 5) | |
| // ... line 24 | |
| ; | |
| } | |
| } |
Así de sencillo. Y, de hecho, déjame que vuelva a poner nuestro volcado para que podamos ver el resultado:
| // ... lines 1 - 9 | |
| class DragonTreasureResourceTest extends KernelTestCase | |
| { | |
| // ... lines 12 - 14 | |
| public function testGetCollectionOfTreasures(): void | |
| { | |
| // ... lines 17 - 18 | |
| $this->browser() | |
| // ... line 20 | |
| ->dump() | |
| // ... line 22 | |
| ->assertJsonMatches('"hydra:totalItems"', 5) | |
| // ... line 24 | |
| ; | |
| } | |
| } |
Pruébalo ahora:
symfony php bin/phpunit
¡Pasa! Y si miras hacia arriba, ¡sí! ¡La respuesta tiene 5 tesoros! Caray, qué fácil.
A continuación: utilicemos JMESPath para afirmar algo más desafiante. Luego retrocederemos y veremos cómo podemos profundizar en Browser para darnos una flexibilidad -y simplicidad- infinitas a la hora de probar JSON.
13 Comments
For those who cannot see any dump after executing tests like me, remember to add into config file debug.yaml
Hey Abraham,
Thanks for this tip!
Cheers!
this statement : '
->assertJsonMatches('"hydra:totalItems"', 5)'generate this error:
My dump json reveal that it has data.
Fixtures launch correctly.
And I also try this : '
->assertJsonMatches('"hydra:totalItems"', '5')'I will investigate this later but if anyone have a explication now he is welcome : )
although the
'5'is type casting your integer to a string... I got the samenullerror when trying to get the value fromhydra:totalItems. so I was looking into the dump and noticed, that currently the property has changed tototalItemsonly. same formemberHey @neostar
Why are you adding additional quotes? IIRC it should be like this
->assertJsonMatches('hydra:totalItems', 5)Cheers!
according to this chapter (see video around 2:20) and the transcript you have to add quotes when dealing with a colon.
see also tests/Functional/DragonTreasureResourceTest.php line 29 or 30 in the "finished" version.
whoops sorry =) my bad
Have you tried
->dump()to check the output?Cheers!
see the comment further up.. it's not about the quotes in the first place. but the fact that the
hydra:prefix is not existing anymore in the newest version.Yes, but I consider that you are all using API Platform bundled with course, which is based on version 3.1, and no one mentions upgrade to the latest version of it.
fair point. at least if somebody is running into the same problem, they will find 2 possible reasons here now.
Agree! Thanks for cooperation!
Have a good day. Happy codding! Cheers!
Hi everyone !
For me, this, it is not working :
I've got this error :
PDOException: SQLSTATE[23000]: Integrity constraint violation: 19 NOT NULL constraint failed: dragon_treasure.owner_idSo, let's do it :
Voilà : It's alive :-)
OK (1 test, 3 assertions)I'm using SQLite, I don't know if it matters.
Hey @DrT
Yes, you need to set the
ownerfield somehow to get rid of that error. In the tutorial we do this inside theDragonTreasureFactory::getDefaults()methodCheers!
"Houston: no signs of life"
Start the conversation!