2016-07-29 90 views
0

我目前正在处理异常处理程序,并创建自己的自定义异常。处理来自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(),因此它不会返回对应的。

非常感谢!

回答

0

我终于找到了解决方案!

正如我所说,响应不是正确的,因为它试图重定向rathen,而不是返回有效的JSON响应。

并通过请求代码会后,我才发现原来我还需要使用wantsJson(),为阿贾克斯()可能不总是如此,所以我修改了我的特点,以这样的:

<?php 

namespace Actuame\Exceptions; 

trait ExceptionTrait 
{ 

    public function response(Request $request) 
    { 
     // Below here, I added $request->wantsJson() 
     $type = $request->ajax() || $request->wantsJson() ? '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); 
    } 

}