A煤n no tienes acceso a esta clase

Crea una cuenta y contin煤a viendo este curso

Show con TDD

31/36
Recursos

Aportes 38

Preguntas 5

Ordenar por:

驴Quieres ver m谩s aportes, preguntas y respuestas de la comunidad? Crea una cuenta o inicia sesi贸n.

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(鈥楪ET鈥,"/api/posts/$post->id");
$response->assertJsonStructure([鈥榠d鈥,鈥榯itle鈥,鈥榗reated_at鈥橾)
->assertJson([鈥榯itle鈥=> $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

  1. Uso de constantes para mejorar legibilidad al usar los HTTP status.
  2. Utilizar postJson() y getJson() en lugar de json() m谩s que nada por gusto personal jeje
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 鈥渜uemar鈥 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);
    }