2 测试发贴 phpunit tdd

安装相关插件
https://github.com/sempro/phpunit-pretty-print

composer require sempro/phpunit-pretty-print --dev

修改phpunit.xml为如下



    
        
            ./tests/Unit
        

        
            ./tests/Feature
        
    
    
        
            ./app
        
    
    
        
        
        
        
        
        
        
        
    

试着运行一下

➜  blog.dock.com phpunit
PHPUnit 7.4.3 by Sebastian Bergmann and contributors.


Tests\Unit\ExampleTest
  ✓ basic test [0.635s]

Tests\Feature\ExampleTest
  ✓ basic test [0.265s]


Time: 1.39 seconds, Memory: 14.00MB

OK (2 tests, 2 assertions)

so cool
接下来开始真正的测试吧
parent::setUp();必不可少,防止父方法被覆盖

thread = factory(\App\Models\Thread::class)->create();
    }
    /**
     * 用户可以看见所有帖子
     * @test
     * @return void
     */
    public function user_can_view_all_threads()
    {
        $response = $this->get('/threads');
        $response->assertStatus(200);
        $response->assertSee($this->thread->title);
    }

    /**
     * 用户可以看见帖子详情页
     * @test
     * @return void
     */
    public function user_can_view_an_thread()
    {
        $response = $this->get($this->thread->path());
        $response->assertStatus(200);
        $response->assertSee($this->thread->title);
    }

}

测试 失败 挖坑待填

➜  blog.dock.com phpunit
PHPUnit 7.4.3 by Sebastian Bergmann and contributors.

Tests\Feature\ThreadTest
  x user can view all threads [0.024s]
  x user can view an thread [0.000s]

开始修复问题 填坑
增加如下两行route

Route::get('/threads', 'ThreadController@index');
Route::get('/threads/{thread}', 'ThreadController@show')

model增加path方法

id;
    }
}

控制器 查看所有 index方法

public function index()
{
        //
        $threads = Thread::latest()->get();

        return view('threads.index', compact('threads'));
 }

相关视图文件

@extends('layouts.app')

@section('content')
Forum Threads
@foreach ($threads as $thread)
@endforeach
@endsection

测试通过

➜  blog.dock.com phpunit
PHPUnit 7.4.3 by Sebastian Bergmann and contributors.

Tests\Feature\ThreadTest
  ✓ user can view all threads [0.752s]
  x user can view an thread [0.113s]

处理查看单个详情页

 public function show(Thread $thread)
    {
        //
        return view('threads.show', compact('thread'));
    }

相关的视图代码

@extends('layouts.app')

@section('content')
    
Some Thread

{{ $thread->title }}

{{ $thread->body }}

@endsection

测试通过,大功告成!

Tests\Feature\ThreadTest
  ✓ user can view all threads [0.660s]
  ✓ user can view an thread [0.112s]

你可能感兴趣的:(2 测试发贴 phpunit tdd)