– 親テーブルの方にテストケースを書く
– modelのmass asignmentは忘れがちなので注意
BookManagementTest.php
public function test_a_new_author_is_automatically_added(){
$this->post('/books', [
'title' => 'Cool Title',
'author' => 'Victor'
]);
$book = Book::first();
$author = Author::first();
$this->assertCount(1, Author::all());
$this->assertEquals($author->id, $book->book_id);
}
Author.php
public function setAuthorAttribute($author){
$this->attributes['author_id'] = Author::firstOrCreate([
'name' => $author,
]);
}
$ phpunit –filter test_a_new_author_is_automatically_added
tests/Unit/AuthorTest.php
namespace Tests\Unit;
// use PHPUnit\Framework\TestCase;
use Tests\TestCase;
use Illuminate\Foundation\Testing\RefreshDatabase;
use App\Author;
class ExampleTest extends TestCase
{
use RefreshDatabase;
public function test_a_dob_is_nullable(){
Author::firstOrCreate([
'name' => 'John Doe'
]);
$this->assertCount(1, Author::all());
}
}
author migration file
Schema::create('authors', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('name');
$table->timestamp('dob')->nullable();
$table->timestamps();
});
public function test_a_new_author_is_automatically_added(){
$this->withoutExceptionHandling();
$this->post('/books', [
'title' => 'Cool Title',
'author' => 'Victor'
]);
$book = Book::first();
$author = Author::first();
$this->assertEquals($author->id, $book->author_id);
$this->assertCount(1, Author::all());
}
$ php artisan make:test BookTest –unit
>>> \Schema::getColumnListing(‘books’);
=> [
“id”,
“title”,
“author”,
“author_id”,
“created_at”,
“updated_at”,
]
Book.php
protected $fillable = ['title', 'author','author_id'];
public function path(){
return '/books/' . $this->id;
}
public function test_an_author_id_is_recorded()
{
Book::create([
'title' => 'Coolest title',
'author' => '',
'author_id' => 1,
]);
$this->assertCount(1, Book::all());
}
$ phpunit –filter test_an_author_id_is_recorded
OK (1 test, 1 assertion)
BooksController.php
rotected function validateRequest(){
return request()->validate([
'title' => 'required',
'author_id' => 'required',
]);
}
Book.php
public function setAuthorIdAttribute($author){
$this->attributes['author_id'] = (Author::firstOrCreate([
'name' => $author,
]))->id;
}
$ phpunit –filter test_a_new_author_is_automatically_added
OK (1 test, 2 assertions)
ぐううう
### 全てのmethodをテストするとき
just run phpunit
$ phpunit
### private function
$response = $this->post('/books', [
'title' => 'Cool Title',
'author_id' => 1
]);
$response = $this->post('/books',$this->data());
private function data() : array{
return [
'title' => 'Cool Title',
'author_id' => 1
];
}
### array_merge
public function test_a_author_is_require(){
$response = $this->post('/books', array_merge($this->data(), ['author_id'=> '']));
$response->assertSessionHasErrors('author_id');
}
OneToOneのテストメソッドでも基本は同じ