CakePHPで404エラーをテストする
テスト対象のController
Controller側で例外を設定し、その発生をテストします。
以下のviewアクション内に設定した例外処理が期待通り発生するかをテストします。
1 2 3 4 5 6 7 8 9 10 11 12 13 | public function view( $id = null) { // $idがfalseの場合例外発生 if (! $id ) { throw new NotFoundException( 'Invalid Post' , 404); } $post = $this ->Post->getPostById( $id ); // $postがfalseの場合例外発生 if (! $post ) { throw new NotFoundException( 'No Post' , 400); } $this ->set( 'post' , $post ); } |
2つ目のNotFoundExceptionでは、2番目の引数に400を渡し、例外発生時にはHTTPステータスコード400が返されるようにしました。
例外の発生をテストする
setExpectedException
を使って例外の発生をテストする方法が書かれています。CakePHPでテストする場合も同様に書くことが可能です。
1 2 3 4 5 6 7 8 9 | public function testViewIdNull( $id = null) { $this ->setExpectedException( 'NotFoundException' , 'Invalid Post' , 404); $result = $this ->testAction( '/posts/view/' . $id ); } public function testViewNoPost( $id = 99999999) { $this ->setExpectedException( 'NotFoundException' , 'No Post' , 400); $result = $this ->testAction( '/posts/view/' . $id ); } |
setExpectedExceptionメソッドを使って、
- 例外の種類
- レスポンスメッセージ
- ステータスコード
発生した例外処理の内容をテストすることが可能です。