2014-09-10 129 views
0

如何在不發送電子郵件的情況下測試此代碼段?Laravel單元測試如何使用電子郵件測試事件而不發送電子郵件

public function forgot() 
    { 
     $isValid = $this->updateForm->valid(Input::only('email')); 
     if ($isValid) { 
      $result = $this->user->forgot($this->updateForm->data()); 
      if (isset($result['user']) && ($result['success'] > 0)) { 
       Event::fire('user.mail.forgot', array('data'=>$result['user'])); 
       return Response::json(array('success'=>1),200); 
      } 
      $error = isset($result['error'])?array_pop($result):trans('user.generror'); 
      return Response::json(array(
       'success'=>0, 
       'errors' => array('error'=>array($error))), 
      200); 
     } 
     return Response::json(array(
        'success' => 0, 
        'errors' => $this->updateForm->errors()), 
        200 
     ); 
    } 

現在我測試:

public function _getSuccess($content) 
{ 
    $json = str_replace(")]}',\n", '', $content); 
    $native = json_decode($json); 
    return $native->success; 
} 
public function _set200($method, $uri, $parameters = array()) 
{ 
    $this->client->setServerParameter('HTTP_X-Requested-With', 'XMLHttpRequest'); 
    $response = $this->call($method, $uri, $parameters); 
    $this->assertResponseStatus(200); 
    return $response; 
} 
public function testUserForgot200Success() 
{ 
    $response = $this->_set200('POST', '/api/v1/users/forgot', array('email' => $this->userEmail)); 
    $this->assertSame(1, $this->_getSuccess($response->getContent())); 
} 

但這種方式我必須設置郵件配置文件在測試文件夾和sustem發送電子郵件:(

回答

1

創建app/config/testing/mail.php文件,並設置假裝真的就可以了:

<?php 

return [ 

    'pretend' => true, 

]; 
5

我需要做的是,在Larave微升5所以萬一有人需要它,這裏有一個解決方案:

config/mail.php替換此:

'pretend' => false,

本:

'pretend' => env('MAIL_PRETEND', false),

然後你就可以覆蓋這個環境變量在phpunit.xml

<php> 
    <env name="APP_ENV" value="testing"/> 
    <env name="CACHE_DRIVER" value="array"/> 
    <env name="SESSION_DRIVER" value="array"/> 
    <env name="QUEUE_DRIVER" value="sync"/> 
    <!-- Add this line: --> 
    <env name="MAIL_PRETEND" value="true" /> 
</php> 

如果需要,您也可以在.env文件中覆蓋它,但它不會影響phpunit。

相關問題