0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

備忘録:Laravel nullの扱いについての学習

Posted at
// 例コード
<?php
namespace App\Services;

use App\Http\Requests\PostRequest;
use App\Models\Post;

class PostService
{
    public function __construct(private Post $post) {}

    /**
     * 投稿情報を取得する
     * @param PostRequest $request
     * @return Post
     */
    public function getPostById(PostRequest $request): Post { /** 検証 */ }
}

利用するテストコード

<?php

namespace Tests\Unit\Service;

use App\Http\Requests\PostRequest;
use App\Models\Post;
use App\Services\PostService;
use Illuminate\Foundation\Testing\DatabaseMigrations;
use Tests\TestCase;

class PostServiceTest extends TestCase
{
    use DatabaseMigrations;

    private PostService $postService;

    public function setUp(): void
    {
        parent::setUp();
        $this->seed();

        $this->postService = $this->app->make(PostService::class);
    }
    
    /**
     * @test
     * @dataProvider testData
     * @return void
     */
    public function test(array $requests): void
    {
        $reqeust = new PostRequest();
        $reqeust->merge($requests);

        $getPost = $this->postService->getPostById($reqeust);


        // 中身を確認
        dump($getPost);
        $this->assertInstanceOf(Post::class, $getPost);
    }

    public static function testData(): array
    {
        return [
            '検証1/存在するpost_id' => [
                ['id' => 1],
            ],
            '検証2/存在しないpost_id' => [
                ['id' => 100],
            ],
        ];
    }
}

検証1 値が見つからないときの対処を行わない

public function getPostById(PostRequest $request): Post 
{ 
    return $this->service->getPostById($request->id)->first();
}

image.png

検証2 return $this->service->getId()->first() ?? new Post

public function getPostById(PostRequest $request): Post 
{ 
    return $this->service->getPostById($request->id)->first() ?? new Post;
}

image.png

検証3 返却値を ?Post にする

public function getPostById(PostRequest $request): ?Post 
{ 
    return $this->service->getPostById($request->id)->first();
}

image.png

考察

検証2は、存在しない値を渡したときに new Post が働いたことで空のPostオブジェクトが返却されたため成功した。
検証3については、存在しない場合null許容を行っているためエラー内容の通り「Failed asserting that null is an instance of class of ~」が出力されている。

個人的検証3のように返却値に ?Post を行うやり方でコードを書こうと思った。理由として下記のようにif文で確認した後に何かコード実行を行う場合、検証2では 空Post を受け取ってしまうため True の処理として実行されてしまうため。

if ($getPost) { .... } 
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?