我目前正在處理異常處理程序,並創建自己的自定義異常。處理來自PHPUnit(Laravel 5.2)的自定義異常
我一直在使用PHPUnit在我的控制器資源上運行測試,但是當我拋出我的自定義異常時,Laravel認爲它來自常規HTTP請求而不是AJAX。
例外基於羯羊它是一個AJAX請求或不返回不同的響應,如下所示:
<?php namespace Actuame\Exceptions\Castings;
use Illuminate\Http\Request;
use Exception;
use Actuame\Exceptions\ExceptionTrait;
class Already_Applied extends Exception
{
use ExceptionTrait;
var $redirect = '/castings';
var $message = 'castings.errors.already_applied';
}
而且ExceptionTrait去如下:
<?php
namespace Actuame\Exceptions;
trait ExceptionTrait
{
public function response(Request $request)
{
$type = $request->ajax() ? 'ajax' : 'redirect';
return $this->$type($request);
}
private function ajax(Request $request)
{
return response()->json(array('message' => $this->message), 404);
}
private function redirect(Request $request)
{
return redirect($this->redirect)->with('error', $this->message);
}
}
最後,我的測試去像這樣(節選失敗的測試)
public function testApplyToCasting()
{
$faker = Factory::create();
$user = factory(User::class)->create();
$this->be($user);
$casting = factory(Casting::class)->create();
$this->json('post', '/castings/apply/' . $casting->id, array('message' => $faker->text(200)))
->seeJsonStructure(array('message'));
}
我的邏輯是這樣的雖然我不認爲錯誤是從這裏
public function apply(Request $request, User $user)
{
if($this->hasApplicant($user))
throw new Already_Applied;
$this->get()->applicants()->attach($user, array('message' => $request->message));
event(new User_Applied_To_Casting($this->get(), $user));
return $this;
}
未來當運行PHPUnit的做,我得到返回的錯誤是
1)CastingsTest :: testApplyToCasting PHPUnit_Framework_Exception:PHPUnit_Framework_Assert的 參數#2(沒有值): :assertArrayHasKey()必須是一個陣列或ArrayAccess接口
/home/vagrant/Code/actuame2/vendor/laravel/framework/src/Illuminate/Foundation/T esting/Concerns/MakesHttpRequests.php:304 /home/vagrant/Code/actuame2/tests/CastingsTest.php:105
而且我laravel.log是在這裏http://pastebin.com/ZuaRaxkL(太大粘貼)
其實我已經發現的PHPUnit沒有實際發送Ajax響應,因爲我ExceptionTrait實際上改變這個響應。運行測試時,它將請求作爲常規POST請求運行,並且運行重定向()響應而不是ajax(),因此它不會返回對應的。
非常感謝!