Upgrade to Pro — share decks privately, control downloads, hide ads and more …

継続的にLaravelのUnitTestを書く上で 気をつけていること

Avatar for stwile stwile
September 28, 2021

継続的にLaravelのUnitTestを書く上で 気をつけていること

Avatar for stwile

stwile

September 28, 2021
Tweet

More Decks by stwile

Other Decks in Technology

Transcript

  1. サンプルコード class FetchTodoService { public function exec(string $user_id, int $todo_id):

    array { $todo_repos = new TodoRepository(); $result = $todo_repos->fetchTodo($todo_id, $user_id); if ($result === []) { throw new NotFoundException('Todoのデータが存在しません'); } return $result; } }
  2. 変更前 class FetchTodoService { public function exec(string $user_id, int $todo_id):

    array { $todo_repos = new TodoRepository(); $result = $todo_repos->fetchTodo($todo_id, $user_id); if ($result === []) { throw new NotFoundException('Todoのデータが存在しません'); } return $result; } }
  3. 変更後 class FetchTodoService { public function exec( string $user_id, int

    $todo_id, TodoRepository $todo_repos, ): array { $result = $todo_repos->fetchTodo($todo_id, $user_id); if ($result === []) { throw new LogicException('Todoのデータが存在しません'); } return $result; } } TodoRepository を外部から注入
  4. テストのサンプル class FetchTodoServiceTest extends TestCase { /** @test */ public

    function データが存在しない場合、空の配列を返すべき (): void { $user_id = 'user_id'; $todo_id = 999999; $todo_repos_mock = Mockery::mock(TodoRepository ::class); $todo_repos_mock ->shouldReceive ('fetchTodo') ->once() ->with($user_id, $todo_id) ->andReturn([]); $service = new TodoService(); parent::expectedException (LogicException ::class); parent::expectExceptionMessage ('Todoのデータが存在しません '); $service->exec($user_id, $todo_id, $todo_repos_mock ); } } 引数を設定 返り値を設定