En laravel 8, el archivo PostFactory se escribiría asi:
public function definition()
{
return [
'title' => $this->faker->sentence
];
}
Entender Laravel
¿Qué es Laravel?
Herramientas necesarias para trabajar con PHP y Laravel
Entendiendo el ciclo de vida de las solicitudes web
Qué es un CRUD y cómo implementarlo
Lógica de controladores y vistas con datos de prueba
Creando un formulario
Comprender los Fundamentos de Laravel
Sistema de rutas y controladores
Uso de Middlewares
Validación de datos (rutas, vistas, formularios y controladores)
Blade: sistema de plantillas avanzado
Trabajando con el componente Laravel/UI
Aprender sobre Eloquent ORM
Eloquent: trabajando con este ORM
Relaciones de tablas
Colecciones y serialización de datos
Formato de valores en tablas y presentación de datos
Crear PlatziPress
Proyecto Blog: presentación y configuración inicial
Creación de tablas, entidades y datos de prueba
Plantillas de trabajo y entendiendo el login
Diseño visual con Bootstrap
Vista index y botones de acción
Implementación del formulario de creación
Implementación del guardado
Creando la función de editar un post
Actualizando nuestros posts
Integrando contenido audiovisual
Construir Proyecto Final: API con TDD (Intermedio)
Introducción al testing
Metodología TDD y testing HTTP
Proyecto API con TDD: presentación y configuración inicial
Store con TDD
Refactorización y validación en Store
Show con TDD
Update y validación con TDD
Delete con TDD
Index con TDD
Protección de una API con Login
Cierre del curso
Aún no tienes acceso a esta clase
Crea una cuenta y continúa viendo este curso
Aportes 38
Preguntas 5
En laravel 8, el archivo PostFactory se escribiría asi:
public function definition()
{
return [
'title' => $this->faker->sentence
];
}
En laravel 8.x cambia el factory
public function test_show()
{
$this->withoutExceptionHandling();
$post = Post::factory()->create();
$response = $this->json(‘GET’,"/api/posts/$post->id");
$response->assertJsonStructure([‘id’,‘title’,‘created_at’])
->assertJson([‘title’=> $post->title])
->assertStatus(200);
}
** vendor/bin/phpunit --testdox**
public function test_show()
{
$this->withoutExceptionHandling();
$post = factory(Post::class)->create();
$response = $this->json('GET', "/api/posts/$post->id"); //id = 1
$response->assertJsonStructure(['id', 'title', 'created_at', 'updated_at'])
->assertJson(['title' => $post->title])
->assertStatus(200); // ok
}
public function test_404_show()
{
$response = $this->json('GET', '/api/posts/1000'); //id = 1000
$response->assertStatus(404); // no existe
}```
En laravel 8.x hay que escribir:
use App\Models\Post;
Aporte de la clase echo con mucho entusiasmo y mucha hambre de aprendizaje 😄
https://www.evernote.com/l/Ap4jk8UWAGJCjL4rskky7ViulhH9ExRb79E/
Laravel 8
public function test_show()
{
$post = Post::factory()->create();
$response = $this->json("GET", "/api/posts/$post->id");
$response->assertJsonStructure(['id', 'title', 'created_at', 'updated_at'])
->assertJson(['title'=> $post->title])
->assertStatus(200); // OK
}
public function test_404_show()
{
$response = $this->json("GET", '/api/posts/1000');
$response->assertStatus(404);
}
Buenas! Dejo por aquí el estado de mi fichero PostControllerTest.php
(Laravel 8)
Hay un par de cambios respecto al código de las clases
namespace Tests\Feature\Http\Controllers\Api;
use App\Models\Post;
use Tests\TestCase;
use Illuminate\Foundation\Testing\RefreshDatabase;
class PostControllerTest extends TestCase
{
use RefreshDatabase;
const HTTP_OK = 200;
const HTTP_CREATED = 201;
const HTTP_NOT_FOUND = 404;
const HTTP_UNPROCESSABLE_ENTITY = 422;
public function test_store()
{
$response = $this->postJson('api/posts', ['title' => 'El post de prueba']);
$response->assertJsonStructure(['id', 'title', 'created_at', 'updated_at'])
->assertJson(['title' => 'El post de prueba'])
->assertStatus(self::HTTP_CREATED);
$this->assertDatabaseHas('posts', ['title' => 'El post de prueba']);
}
public function test_validate_title()
{
$response = $this->postJson('api/posts', ['title' => '']);
$response->assertStatus(self::HTTP_UNPROCESSABLE_ENTITY)
->assertJsonValidationErrors('title');
}
public function test_show()
{
$post = Post::factory()->create();
$response = $this->getJson("api/posts/{$post->id}");
$response->assertJsonStructure(['id', 'title', 'created_at', 'updated_at'])
->assertJson(['title' => $post->title])
->assertStatus(self::HTTP_OK);
}
public function test_invalid_post()
{
$response = $this->getJson('api/posts/1000');
$response->assertStatus(self::HTTP_NOT_FOUND);
}
}
Genial! Me esta empezando a gustar desarrollar con pruebas xD Aquí dejo mis métodos del test de show:
public function test_show() {
$post = Post::factory()->create();
$response = $this->json("GET", "/api/posts/$post->id");
$response->assertJsonStructure(["id", "title", "created_at", "updated_at"])
->assertJson(["title" => $post->title])
->assertStatus(200); // Ok
}
public function test_404_show() {
$response = $this->json("GET", "/api/posts/1000");
$response->assertStatus(404); // Ok
}
Deben tener en cuenta que Laravel en su version 8.x ha tenido varios cambios, como por ejemplo el helper factory, la manera de crear factories y ahora los modelos se crean dentro de la carpeta models en la carpeta app, lo que hace que al usar los modelos deban seguir la nomenclatura App\Models[Modelo].
Aqui usando el comando php artisan test
![]()
1) Tests\Feature\Http\Controllers\Api\PostControllerTest::test_show
TypeError: Argument 1 passed to Illuminate\Database\Grammar::parameterize() must be of the type array, string given, called in C:\xampp\htdocs\ApiPlatziLaravel\vendor\laravel\framework\src\Illuminate\Database\Query\Grammars\Grammar.php on line 869
Las pruebas creadas para esta clase.
public function test_show()
{
$post = factory(Post::class)->create();
$response = $this->json('GET',"api/posts/$post->id");
$response->assertJsonStructure(['id','title','created_at','updated_at'])
->assertJson(['title' =>$post->title])
->assertStatus(200);
}
public function test_404_show()
{
$response = $this->json('GET','api/posts/1000');
$response->assertStatus(404);
}
Que tal amigos, queria compartir mis anotaciones de este test, por si a alguien le sirve
public function test_show()
{
// Create a post
$post = Post::factory()->create();
// Request that post based on ID
$response = $this->json('GET', "/api/posts/$post->id"); // id = 1
// Checks if post has id, title, created_at and updated_at
$response->assertJsonStructure(['id', 'title', 'created_at', 'updated_at'])
->assertJson(['title' => $post->title]) // Checks title matches
->assertStatus(200); // Okay and creates a resource
}
public function test_404_show()
{
// No need to create a post since we need to prove a 404 error
$response = $this->json('GET', '/api/posts/1000'); // id = 1000
$response->assertStatus(404); // Returns a 404
}
El codigo utilizado para el metodo show:
public function test_show()
{
//$post = factory(Post::class)->create(); //laravel 6
$post = Post::factory()->create();
$response = $this->json('GET', "/api/posts/$post->id"); //id=1
$response->assertJsonStructure(['id','title','created_at', 'updated_at'])
->assertJson(['title' => $post->title])
->assertStatus(200); //Ok
}
public function test_404_show()
{
$response = $this->json('GET', '/api/posts/1000');
$response->assertStatus(404); //not found
}
}
Hasta aqui voy bien
#Api
#Test
public function test_show()
{
$post = factory(Post::class)->create();
$response = $this->json('GET',"/api/posts/$post->id"); //id=1
$response->assertJsonStructure(['id','title','created_at','updated_at'])
->assertJson(['title' => $post->title])
->assertStatus(200); //OK
}
public function test_404_show()
{
$response = $this->json('GET','/api/posts/1000'); //id=1
$response->assertStatus(404); //Recurso no encontrado
}
Código pruebas en el método show =>
public function test_show(){
$this->withoutExceptionHandling();
$post = Post::factory()->create();
$response = $this->json('GET',"/api/posts/$post->id");
$response->assertJsonStructure(['id','title','created_at'])
->assertJson(['title'=> $post->title])
->assertStatus(200);
}
public function test_404_show(){
$response = $this->json('GET',"/api/posts/1000");
$response->assertStatus(404);
}
/**
* Feature for show a post test
*
*/
public function test_show()
{
$post = factory(Post::class)->create();
$response = $this->json('GET', "/api/posts/$post->id");
$response->assertJsonStructure(['id', 'title', 'created_at', 'updated_at'])
->assertJson(['title' => $post->title])
->assertStatus(200); //OK
}
/**
* Feature for not available show a post test
*
*/
public function test_404_show()
{
$response = $this->json('GET', '/api/posts/1000');
$response->assertStatus(404); //Not available post
}
Cumpliendo con lo indicado por el profe:
public function test_show()
{
$this->withoutExceptionHandling();
$post = Post::factory()->create();
$response = $this->json('GET', "/api/posts/$post->id"); // id =1
$response->assertJsonStructure(['id','title', 'created_at','updated_at'])
->assertJson(['title' => $post->title])
->assertStatus(200); //OK creado un recurso
}
public function test_404_show()
{
//$this->withoutExceptionHandling();
//$post = Post::factory()->create();
$response = $this->json('GET', '/api/posts/1000'); // id =1
$response->assertStatus(404); //OK creado un recurso
}
Me presento con errores en las dos funciones que se crearon en esta clase.
El primero test_show()
Me muestra el siguiente error
• Tests\Feature\Http\Controllers\Api\PostControllerTest > validate title
Illuminate\Validation\ValidationException
The given data was invalid.
El segundo test_404_show()
Me muestra el siguiente error
• Tests\Feature\Http\Controllers\Api\PostControllerTest > 404 show
Illuminate\Database\Eloquent\ModelNotFoundException
No query results for model [App\Models\Post] 1000
Ya he tratado de lidiar con este error por media hora y no encuentro solución.
Agradecería si alguien me explica la solución a estos.
Todo ok
public function test_404_show()
{
//$this->withoutExceptionHandling();
$post = factory(Post::class)->create();
$response = $this->json('GET', "/api/posts/1000"); //id=1
$response->assertStatus(404);//ok, creado un recurso
}```
aquí esta el resultado funcionando en consola 😄 :
public function test_show()
{
//Se genera un post utilizando el factory y se guarda en la variable post
$post = factory(Post::class)->create();
//Se pide mediante GET el post, enviando la propiedad id de la variable post
$response = $this->json('GET',"/api/posts/$post->id"); // id = 1
//Se verifica que la estructura del JSON que se recibe sea la especificada, que el titulo coincida y que el estatus sea 200
$response->assertJsonStructure(['id','title','created_at','updated_at'])
->assertJson(['title' => $post->title])
->assertStatus(200);//OK,
}
public function test_404_show()
{
//Se envia un ID que no existe en la BD
$response = $this->json('GET','/api/posts/1000'); // id = 1000
//Se espera recibir un status 404 not found
$response->assertStatus(404);//OK,
}
Resultado de las dos pruebas:
Muy bien con las pruebas del método Show, ahora vamos con el método Update.
Acá mi prueba:
public function postCanShow()
{
$post = factory(Post::class)->create();
$response = $this->json('GET', "/api/posts/$post->id", [
'title' => ''
]);
$response->assertJsonStructure(['id','title', 'created_at', 'updated_at'])
->assertJson(['title' => $post->title])
->assertStatus(200);
}
/**
*
* @return void
* @test
*/
public function cantShowNonexistentPost()
{
$response = $this->json('GET', '/api/posts/1000', [
'title' => ''
]);
$response->assertStatus(404);
}
Pruebas
public function testShow(){
$post = factory(Post::class)->create();
$response = $this->json('GET', "/api/posts/$post->id");
$response->assertJsonStructure(['id', 'title', 'created_at', 'updated_at'])
->assertJson(['title' => $post->title])
->assertStatus(200);
}
public function test404Show(){
$response = $this->json('GET', '/api/posts/1000');
$response->assertStatus(404);
}
Controlador
public function show(Post $post)
{
return response()->json($post);
}
Consola
PASS Tests\Feature\Http\Controllers\Api\PostControllerTest
✓ store
✓ validate title
✓ show
✓ 404 show
Tests: 6 passed
Time: 0.53s
use Symfony\Component\HttpFoundation\Response;
//PostController.php
/**
* Display the specified resource.
*
* @param \App\Post $post
* @return \Illuminate\Http\Response
*/
public function show(Post $post)
{
return response()->json($post, Response::HTTP_OK);
}
//PostControllerTest.php
public function test_show_post()
{
$this->withoutExceptionHandling();
$post = factory(Post::class)->create();
$response = $this->json('GET', "/api/posts/$post->id");
$response->assertJsonStructure([
'id', 'title', 'created_at', 'updated_at'
])->assertJson(['title' => $post->title])
->assertStatus(Response::HTTP_OK); //Ok
}
public function test_404_show_posts()
{
$response = $this->json('GET', '/api/posts/1000');
$response->assertStatus(Response::HTTP_NOT_FOUND);
}
En vez de “quemar” los códigos de respuesta http, utilicé constantes de la clase Response de Symfony, por si más adelante se cambian.
public function test_show(){
$post = Post::factory()->create();
$response = $this->json('GET', "/api/posts/".$post->id);
$response->assertJsonStructure([
'id',
'title',
'created_at',
'updated_at'
])
->assertJson(['title' => $post->title])
->assertStatus(200);
}
public function test_404(){
$response = $this->json('GET', '/api/posts/1000');
$response->assertStatus(404);
}
para no hardcodear routas en los tests, por si se cambian alguna vez los paths se puden usar cosas como:
$response = $this->json('GET', route('posts.show', $post));
Test 404
public function test_404_show()
{
$response = $this->json('GET', '/api/posts/1');
$response->assertStatus(404);
}```
public function test_show()
{
// $this->withoutExceptionHandling();
$post = Post::factory()->create();
$response = $this->json('GET', "/api/posts/$post->id");
$response->assertJsonStructure(['id', 'title', 'created_at', 'updated_at'])
->assertJson(['title' => $post->title])
->assertStatus(200);
}
public function test_404_response()
{
$response = $this->json('GET', '/api/posts/1000'); // llamo a un post que no exista
$response->assertStatus(404);
}
¿Quieres ver más aportes, preguntas y respuestas de la comunidad? Crea una cuenta o inicia sesión.