Akita Nakarmi
@nakarmi.akita
TDD is a software development discipline where developers write test cases for features before writing any code.
Write a test, Watch it fail
Write enough code to pass the test
Improve on the code
Update your phpunit.xml file
//set enviroments for testing
<env name="DB_CONNECTION" value="sqlite"/>
<env name="DB_DATABASE" value=":memory:"/>
<env name="API_DEBUG" value="false"/>
<env name="MAIL_DRIVER" value="log"/>
<ini name="memory_limit" value="512M" />
abstract class TestCase extends BaseTestCase
{
use CreatesApplication, DatabaseMigrations, DatabaseTransactions;
protected $faker;
/**
* Set up the test
*/
public function setUp()
{
parent::setUp();
$this->faker = Faker::create();
}
/**
* Reset the migrations
*/
public function tearDown()
{
$this->artisan('migrate:reset');
parent::tearDown();
}
}
class PostApiTest extends TestCase
{
public function test_it_can_create_a_post()
{
//Arrange
$data = [
'title' => $this->faker->sentence,
'content' => $this->faker->paragraph
];
//Act
$this->post(route('posts.store'), $data)
//Assert
->assertStatus(201)
->assertJson($data);
}
}
Error: Route not found
//posts route
Route::post('posts', 'PostsApiController@store')->name('posts.store');
Error: PostApiController does not Exist
//create controller
php artisan make:controller PostsApiController
class PostsApiController extends Controller
{
//post method to store post
public function store() {
dd('here!');
}
}
//create post from the request data
public function store(Request $request) {
$data=$request->all();
$post=Post::create($data);
return $post;
}
Error: Opps! Post Class Not Found
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
protected $fillable=
[
'title',
'content',
];
}
Error: No Post Table Found
public function up()
{
Schema::create('posts', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('title');
$table->text('content');
$table->timestamps();
});
}
Test pass successfully!
<?php
namespace App\Articles\Requests;
use Illuminate\Foundation\Http\FormRequest;
class PostAddRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
return [
'title' => 'required',
'content' => 'required'
];
}
}
public function test_tile_is_required(){
$data = [
'content' => $this->faker->paragraph,
];
$this->post(route('posts.store'), $data)
->assertStatus(422);
}
public function test_content_is_required(){
$data = [
'title' => $this->faker->sentence,
];
$this->post(route('posts.store'), $data)
->assertStatus(422);
}
Testable code looks a lot like good code.
Start with an assert
Do not write application logic in tests
Do not worry about testing "RIGHT" or which library to use
Not every feature can and should be tested
Just get started...